Andrew's Digital Garden

Use unknown over any in Typescript

unknown is the type-safe variant of any. Both allow any values to be assigned to them, but unknown isn't assignable to anything, where as any is. This means that to use a variable of type unknown, it requires a type assertion or narrowing to a more specific type first.

Essentially this can be any value, but you must perform a type check before using it. As a blanket rule, every any should be replaced with an unknown.

let vAny: any = 10; // We can assign anything to any let vUnknown: unknown = 10; // We can assign anything to unknown just like any let s1: string = vAny; // Any is assignable to anything let s2: string = vUnknown; // Invalid we can't assign vUnknown to any other type (without an explicit assertion) vAny.method(); // ok anything goes with any vUnknown.method(); // not ok, we don't know anything about this variable

[[js]] [[ts]]

Use `unknown` over `any` in Typescript