unknown
is the type-safe counterpart of any.
Anything is assignable to unknown
, but unknown
isn’t assignable to anything but itself and any
without a type assertion or a control flow based narrowing.
Likewise, no operations are permitted on an unknown
without first asserting or narrowing to a more specific type.
function f1(a: any) {
a.b(); // OK
}
function f2(a: unknown) {
// Error: Property 'b' does not exist on type 'unknown'.
a.b();
}
unknown type without type assertion or narrowing
const value = '0';
function whatIsUnknown(unknownValue: unknown) {
const newValue = unknownValue + 1; // 'unknownValue' is of type 'unknown'.
return newValue;
};
console.log(whatIsUnknown(value));
unknown type with narrowing
const value = '0';
function whatIsUnknown(unknownValue: unknown) {
if (typeof unknownValue === 'number') {
return unknownValue + 1;
} else if (typeof unknownValue === 'string') {
return unknownValue;
}
return null;
};
console.log(whatIsUnknown(value));
Unknown type forces you to do type check to make your code safer.