TypeScript Special Types
TypeScript Special Types: unknown, any, void, and never
TypeScript adds four special types that JavaScript lacks: any, unknown, void, and never. Choosing unknown over any and using never for exhaustive checks prevents silent runtime crashes across large apps.
Think of unknown as the type-safe counterpart to any: both accept any value, but unknown forces you to verify the value's type before touching its properties.
Comparing Special Types Side by Side
| Type | Accepts Any Value? | Requires Narrowing Before Use? | Primary Purpose |
|---|---|---|---|
any |
Yes | No (disables checking!) | Last-resort escape hatch |
unknown |
Yes | Yes (typeof, instanceof) |
Safe untrusted input (JSON.parse) |
void |
undefined only |
N/A | Functions with no return value |
never |
Nothing | N/A | Throwing functions & exhaustive checks |
Using unknown and never in Practice
function parseMessage(raw: unknown): string {
if (typeof raw === "string") {
return raw.trim();
}
if (raw instanceof Error) {
return raw.message;
}
return "Unknown payload";
}
function fail(reason: string): never {
throw new Error(reason);
}
console.log(parseMessage(" ready "));
Exhaustive Checking with never
Assigning an unhandled union branch to const check: never = status makes the compiler fail immediately whenever a teammate adds a new union option and forgets to handle it.
Common Mistakes to Avoid
- Defaulting to
anywhenever a type error feels annoying: Everyanyturns off type checking for everything that touches it downstream. - Confusing
voidwithnever: Avoidfunction returns normally without a meaningful value; aneverfunction never finishes (it always throws or loops forever). - Forgetting
useUnknownInCatchVariables: Modernstrictmode typescatch (err)asunknowninstead ofany, protecting you from readingerr.messageon non-Error throws.
Frequently Asked Questions
When is any actually acceptable?
Temporary migration of legacy JavaScript files or low-level generic wrappers where unknown cannot express the constraint.
Can a void function still execute return;?
Yes. return; (with no value) or reaching the end of the function body is valid for void.
Why does an empty array sometimes infer as never[]?
Under strictNullChecks, const list = [] with no type annotation can infer never[] if never pushed to, blocking future .push("a") calls unless typed as string[].
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.