Any and unknown
Concept and syntax
Both any and unknown can hold values of arbitrary types. With any, many operations are accepted without checking; with unknown, access must be justified by a type check. Use unknown at an uncertain boundary, then inspect it with typeof and handle unsupported values. The guard is executable JavaScript; it narrows the static type within the branch. An any annotation does not validate or transform data.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
function size(value: unknown): number { if (typeof value === "string") return value.length; return 0;}console.log(size("tea"), size(8));Expected output (one line per log):
3 0Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
Expected compiler diagnostic: TS18046. An unknown value might not have length. Guard it before reading the property.
Practice and recap
Extend size to return the length only for strings and -1 for all other inputs. Check an empty string and a number.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Any and unknown — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
Which annotation preserves the need to check an arbitrary input?
What does typeof value === "string" accomplish?
What must happen before reading value.length?
function size(value: unknown) { return value.length; }