Use nonstrict with unknown instead of any
See original GitHub issueCurrently when .nonstrict()
is used, [k: string]: any
appears on the inferred type. Is it possible to use [k: string]: unknown
instead? The problem of using any
is that TypeScript allows you to do anything on any property. If you have a typo on the property name, an unexpected undefined
will appear at runtime. If unknown
is used, at least TypeScript can report an error when you try to use it or assign it to a different variable.
This feature request is similar to https://github.com/vriad/zod/issues/104. I am not sure if this issue will be considered a duplicate of it, but I think .nonstrict()
will be much safer to use if it uses unknown
instead of any
by default.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:6 (2 by maintainers)
Top Results From Across the Web
Typescript: why you should use unknown instead of any
The unknown type, when assigned to a variable, means that a variable type is not known. And typescript doesn't allow you to use...
Read more >'unknown' vs. 'any' - typescript - Stack Overflow
To answer your question of when should you use unknown over any : This is useful for APIs that want to signal “this...
Read more >Strict mode - JavaScript - MDN Web Docs
To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict'; ) before any other statements.
Read more >Typescript - why to use "unknown" instead of "any"
Trying to reassign unknown to a variable of type string or number will throw an error (as mentioned, it can only be reassigned...
Read more >strict - TSConfig Option - TypeScript
All of the common types in TypeScript ... An overview of building a TypeScript web app. TSConfig Options. All the configuration options for...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I think not having index signatures at all is a better idea. I don’t want to use unknown keys that weren’t validated by zod schema. Having
[index: string]: unknown
can still cause some problems. You can make a typo andunknown
type will be used. If the function not that strict, you may not even notice it. Good example is a string constructor (via backquotes)This will not cause typescript to stall here.
Zod 2 is now in beta and sidesteps this issue by getting rid of index signatures altogether. Objects are “nonstrict” by default (in that they allow unknown keys) but the inferred type contains no index signature unless you use the
.catchall()
method to provide one: https://github.com/vriad/zod/tree/v2#catchall