TypeScript Reference ยท Concepts and Comparisons
any versus unknown in TypeScript
Compare any and unknown: what each allows, why unknown is the safe escape hatch, how to narrow it, and where any still appears.
Both any and unknown accept every value. The difference is what you may do afterwards. A value of type any switches the type checker off for that value: you can call it, index it, add to it and assign it anywhere, and nothing is verified. A value of type unknown is the opposite: you can hold it and pass it along, but you must narrow it before using it.
Prefer unknown for data whose shape you do not know. Use any only as a deliberate, short-lived workaround.
let a: any = "text"; let u: unknown = "text"; a.foo(); // compiles, fails at run time // u.foo(); // error TS18046: 'u' is of type 'unknown'.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Comparison
any |
unknown |
|
|---|---|---|
| Assign any value to it | Yes | Yes |
| Assign it to other types | Yes (except never) |
Only to unknown and any |
| Property access, calls, arithmetic | Allowed, unchecked | Error until narrowed |
Narrowing with typeof, in, guards |
Not needed | Required |
| Spreads unchecked values | Yes, it is contagious | No |
| In unions | any absorbs the other members |
unknown absorbs the other members, too |
| In intersections | any & T is any |
unknown & T is T |
Usage notes
anyis contagious. Anything derived from ananyvalue (property reads, call results) is alsoany, so one escape spreads through the code.- Narrow
unknownwithtypeof,instanceof,in, equality, a custom type guard or a validation library; see unknown. - Catch clauses: with
useUnknownInCatchVariables(part ofstrict),catch (e)givesunknown; see useUnknownInCatchVariables. noImplicitAnymakes accidentalanyan error; explicit: anyremains allowed.as anyis the largest hammer. Oftenas unknown as Tis more honest because it states the lie, but both bypass the check.- Generic constraints:
T extends unknownis the default;T extends anyhas the same effect, but onlyunknowndocuments intent. - ESLint rules such as
no-explicit-anyandno-unsafe-*help find leaks. - Third-party JSON,
fetch().json()and event data are classic places to chooseunknown.
Related
- any, unknown, never, noImplicitAny
- Lesson: any, unknown and never