Sub topic 13
Use `unknown` and assertions instead of `any`
Assume you know JavaScript functions, objects, and JSON.parse, and that your project already compiles a mix of .js and .ts files. This chapter focuses on values whose shape is not known yet, such as data from a file, API, or JavaScript library.
Why `any` hides migration problems
any tells TypeScript to stop checking a value. You can read any property, call it as a function, or pass it anywhere. This may make migration errors disappear, but it also allows runtime errors:
function printName(value: any): void {
console.log(value.name.toUpperCase());
}
printName({ name: 42 }); // TypeScript accepts this; JavaScript fails at runtimeunknown is safer. It means “a value exists, but its type has not been verified.” You must check an unknown value before using it.
function printName(value: unknown): void {
if (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string"
) {
console.log(value.name.toUpperCase());
}
}
printName({ name: "Ada" });The check narrows the value. After the condition succeeds, TypeScript knows that value.name is a string.
Use assertions only when you know more
A type assertion tells TypeScript to treat a value as a particular type. It uses the as syntax. An assertion changes compile-time checking only. It does not validate or convert the value at runtime.
interface Config {
port: number;
}
const data: unknown = JSON.parse('{"port":3000}');
const config = data as Config;
console.log(config.port);This assertion is safe only if the JSON always has a numeric port. If the input is {"port":"3000"}, TypeScript still accepts the assertion, but the program receives the wrong runtime value.
Prefer checking before asserting:
interface Config {
port: number;
}
function parseConfig(text: string): Config {
const data: unknown = JSON.parse(text);
if (typeof data !== "object" || data === null) {
throw new Error("Config must be an object");
}
const record = data as Record<string, unknown>;
if (typeof record.port !== "number") {
throw new Error("Config.port must be a number");
}
return { port: record.port };
}
console.log(parseConfig('{"port":3000}'));Record<string, unknown> describes an object with string keys and values that still need checking. The assertion is narrow and immediately followed by validation.
Common migration errors
- Replacing every
anywithas SomeTypeonly moves the problem. - Assuming
JSON.parsereturned the expected object skips runtime validation. - Using a broad assertion such as
value as Usercan hide missing properties. - Returning
unknownwithout documenting how callers should narrow it makes an API difficult to use.
A good migration path is to start with unknown, add a runtime check, and use a small assertion only where TypeScript cannot express a fact that the check already established.
Exercise
Why is unknown safer than any for the result of JSON.parse?
Show answer
TypeScript requires an unknown value to be checked before it is used, while any allows unchecked property access and calls.