Skip to content

unknown type application scenario

About 246 wordsLess than 1 minute

typescript

2022-04-02

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 any

This 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 error
'foo' is of type 'unknown'.
const
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
'input' is of type 'unknown'.
}