unknown type application scenario
The unknown type represents a type that cannot be predefined. In many scenarios, it can replace the function of the any type while retaining the ability of static checking.
Type conversion
const num: number = 10
;(num as unknown as string).split('')
This can be statically checked like anyThis example shows that the role of the unknown type is very similar to that of the any type. You can convert it to any type. The difference is that, any can call any method during static compilation, but the unknown type cannot call any method during static compilation.
const foo: unknown = 'string'
foo.substr(1) // static check fails and reports an errorconst bar: any = 10
bar.substr(1)Replace any
In most cases, we can choose to use unknown instead of any to avoid the failure of static type checking caused by using any.
For example, avoid using any as a function parameter type and use unknown instead.
Using any, static check fails:
function test(input: any): number {
if (Array.isArray(input)) {
return input.length
}
return input.length
}Using unknown, static check correctly infers:
function test(input: unknown): number {
if (Array.isArray(input)) {
// Type guard identifies input as array type
return input.length
}
// Input is unknown type, static check reports error
return input.length}