Sub topic 13
Use unknown and assertions instead of any
This chapter assumes you have renamed a file to .ts, you can read basic compiler errors, and you know how to write interfaces and type annotations. When you convert a file, any is the quickest way to make an error disappear. It is also the way to lose the benefit of the conversion. This chapter covers the alternatives: unknown, narrowing, type guards, and type assertions.
Why any is a problem
A value of type any opts out of type checking. You can read any property from it, call it, or pass it anywhere, and the compiler accepts all of it. The checks you migrated to get are skipped for that value.
any also spreads. A value derived from an any is usually any as well, so one loose annotation can disable checking across a whole call chain.
const settings: any = JSON.parse('{"port": 8080}');
// Typo: "prot" instead of "port". The compiler accepts it.
const port = settings.prot;
// port is also any, so this compiles and throws a TypeError at runtime.
console.log(port.toFixed(0));The standard library produces any in several places. JSON.parse returns any, and so does response.json() in fetch. Values read from untyped libraries can be any too. Watch for these entry points, because they let any into code that otherwise looks typed.
unknown: the safe counterpart
unknown also means "could be anything". The difference is that you can do nothing with an unknown value until you prove what it is. Any value can be assigned to unknown. Reading properties, calling it, or passing it where a specific type is expected is an error.
const data: unknown = JSON.parse('{"port": 8080}');
// Uncommenting the next line gives an error saying 'data' is of type 'unknown'.
// console.log(data.port);
console.log(typeof data); // "object"The compiler now forces the check that the JavaScript code skipped. For a converted file, that check is where the real bugs surface.
| Row | `any` | `unknown` |
|---|---|---|
| Assign any value to it | Yes | Yes |
| Read properties or call it | Yes, unchecked | No, until narrowed |
| Assign it to a typed variable | Yes, unchecked | No, until narrowed |
| Effect on surrounding code | Spreads | Contained |
Narrow unknown with checks
You narrow unknown with the same tools you used for null checks in earlier chapters: typeof, instanceof, Array.isArray, equality checks, and the in operator.
function describe(value: unknown): string {
if (typeof value === "string") {
return value.toUpperCase();
}
if (typeof value === "number") {
return value.toFixed(2);
}
if (Array.isArray(value)) {
return "array of " + value.length;
}
return "unsupported";
}
console.log(describe("hello"));
console.log(describe(3.14159));
console.log(describe([1, 2, 3]));
console.log(describe(null));Inside each if block, the compiler treats value as the narrowed type. After the last check, the function falls through to a default. That default is the case the original JavaScript probably never handled.
Array.isArray narrows to any[], not unknown[]. If you want to keep the elements unchecked, assign the result to a variable typed unknown[].
Validate object shapes with a type guard
typeof only tells you a value is "object". To check that it has the right properties, write a type guard. A type guard is a function whose return type is a type predicate, written value is Config. When it returns true, the compiler narrows the argument to Config at the call site.
interface Config {
port: number;
host?: string;
}
function isConfig(value: unknown): value is Config {
if (typeof value !== "object" || value === null) {
return false;
}
const record = value as Record<string, unknown>;
return (
typeof record.port === "number" &&
(record.host === undefined || typeof record.host === "string")
);
}
function loadConfig(text: string): Config {
const data: unknown = JSON.parse(text);
if (!isConfig(data)) {
throw new Error("Invalid config");
}
return data;
}
console.log(loadConfig('{"port": 8080}'));The guard contains one assertion, value as Record<string, unknown>. That assertion is acceptable because the lines before it have already established that value is a non-null object. The guard then checks each property.
The compiler does not verify the body of a type guard. If you write return true, it accepts the guard and every caller trusts it. Keep guards small, and keep them in step with the interface they describe. For large schemas, a validation library is easier to maintain than hand-written guards.
Type assertions: what they do and do not do
A type assertion, written expr as Type, tells the compiler to treat a value as a given type. It does not check anything at runtime, and it emits no code. If you are wrong, the program fails later and somewhere else.
interface Config {
port: number;
}
// Compiles, but nothing checks the shape of the parsed value.
const config = JSON.parse('{"port": "8080"}') as Config;
// The type says number. The runtime value is a string.
console.log(typeof config.port); // "string"This is the same problem as any, with a type name on top. The compiler now reports config.port as a number while it holds a string, which is arguably worse than any, because readers trust the annotation.
Assertions are acceptable when you know something the compiler cannot. Common cases:
- Narrowing a DOM lookup:
document.getElementById("port") as HTMLInputElement | null. - Asserting inside a type guard, after the real checks, as in
isConfigabove. - Test code that builds a partial object on purpose.
The compiler restricts assertions to types that sufficiently overlap. Asserting a string as a number is an error. You can bypass the restriction with a double assertion, value as unknown as Target. Treat that as a warning sign. It silences the compiler in exactly the case where the compiler believes you are wrong.
The non-null assertion value! is a narrower form. It removes null and undefined from a type, and it carries the same risk. If you use it, add a comment stating why the value cannot be missing.
Other places any hides
Several common patterns produce any or unknown without you writing either.
- Catch clauses. In older configurations the
errorincatch (error)isany. Withstricton (throughuseUnknownInCatchVariables), it isunknown. You can annotate it yourself today, and the code works in both modes. - Rest parameters and callbacks. Parameters you do not annotate may become implicit
any. Chapter material onnoImplicitAnycovers these. - Untyped imports. A package without declarations may be treated as
anyas a whole, which is why the previous step installs@typespackages.
function loadConfig(text: string): { port: number } {
const data: unknown = JSON.parse(text);
if (
typeof data === "object" &&
data !== null &&
"port" in data &&
typeof data.port === "number"
) {
return { port: data.port };
}
throw new Error("Invalid config");
}
try {
loadConfig("{oops");
} catch (error: unknown) {
if (error instanceof Error) {
console.error(error.message);
} else {
console.error(String(error));
}
}The "port" in data check works on unknown that has been narrowed to object. It needs TypeScript 4.9 or later to narrow data.port directly. On older versions, use the Record<string, unknown> cast from the guard above.
Choosing between them
Using any is still allowed during a migration. The rule is that each use is deliberate and findable. Searching for : any and as any should show you the remaining debt. Strict mode and linting, covered later, make that debt visible and then block new instances.
Summary of the working rules
- Type anything that crosses a trust boundary as
unknown, then narrow it. - Prefer narrowing and type guards over assertions.
- Use
asonly for facts the compiler cannot see, and never for external data. - Avoid
as unknown as Tunless you can explain why the types genuinely do not overlap. - Mark unavoidable
anywith a comment so it can be found and removed later.
Exercise
A converted function does const user = JSON.parse(body) as User; and later calls user.name.toUpperCase(). It crashes in production when body is {"id": 4}. Why did the compiler not catch this, and how would you change the code?
Show answer
The as User assertion tells the compiler to trust the shape. It generates no runtime check, so user.name is typed as string even though it is undefined. Change the code to const data: unknown = JSON.parse(body); and pass it through a type guard such as isUser(data), which checks that name is a string. Throw an error, or return a failure result, when the guard returns false.
Exercise
What is the practical difference between let x: any and let x: unknown when you try to write x.length?
Show answer
With any, the code compiles and fails at runtime if x has no length. With unknown, the compiler reports an error until you narrow x, for example with typeof x === "string" or Array.isArray(x).