Unknown vs Any in TypeScript
With examples
Type Safety
unknown
is the type-safe counterpart of any
.
While any
says: "this can be anything, do whatever you want with it"
// Using any
const value: any = 'abc';
value.trim();
TypeScript// Using any
const value: any = 'abc';
value.trim();
unknown
says: "this can be anything, check what it is before using it"
// Using unknown
const value: unknown = 'abc';
value.trim();
TypeScript// Using unknown
const value: unknown = 'abc';
value.trim();
This forces the developer to use type guards to safely narrow the type before performing any operations, thus ensuring type safety.
// Using unknown
const value: unknown = 'abc';
if (typeof value === 'string') {
value.trim();
}
TypeScript// Using unknown
const value: unknown = 'abc';
if (typeof value === 'string') {
value.trim();
}
Conclusion
References are below.
This article is part of my TypeScript Narrowing Series, where we go from fundamentals to advanced use cases. You can read the full series for free here.
Have a great day, and I'll see you soon!