A test reads a response from the Shelf API and checks the number of copies.
const body = JSON.parse('{"title":"Dune","copies":3}');
console.log(body.copyCount.toFixed(0));
TypeError: Cannot read properties of undefined (reading 'toFixed')
The field is called copies, and the code reads copyCount. The compiler reported nothing. The wording of the run-time error is from the engine in Node and Chrome.
Every lecture so far showed the compiler finding this kind of mistake. Here it could not, because of one type.
any
JSON.parse can return anything, so its return type is any. The type any means "do not check this value". You may read any field of it, call it, and put it into a variable of any type.
const body = JSON.parse('{"title":"Dune","copies":3}');
const copies: number = body.title;
const first: string = body.authors[0].name;
body.save();
None of these lines is correct, and all of them compile. Notice the first one. copies is annotated as a number and now holds text. The any did not stay inside body. It went into every value made from it.
You rarely write any yourself. It arrives from outside.
JSON.parsereturns it.- A response body does too. This example is checked against Playwright's own types.
import type { APIResponse } from "@playwright/test";
export async function copiesOf(response: APIResponse): Promise<number> {
const body = await response.json();
return body.copyCount;
}
That compiles. response.json() cannot know what the server sent, so the result is not checked.
unknown
unknown also accepts every value. The difference is on the other side: you cannot use an unknown value until you have checked what it is.
const body: unknown = JSON.parse('{"title":"Dune","copies":3}');
console.log(body.copies);
books.ts(2,13): error TS18046: 'body' is of type 'unknown'.
A check with typeof satisfies the compiler, as it did for unions in lecture 8.
function titleFrom(text: string): string {
const value: unknown = JSON.parse(text);
if (typeof value !== "string") {
throw new Error("Expected a title, received " + typeof value);
}
return value;
}
console.log(titleFrom('"Dune"'));
console.log(titleFrom("42"));
Dune
Error: Expected a title, received number
The first call returns the title. The second stops with the message the helper chose, because 42 is not text.
After the if, the compiler knows value is text. This is the first code in the track where the type and the run-time value are certain to agree. The check runs, so it is still there after the types are removed.
Annotate a parsed value as unknown. It costs you a check, and the check is what makes the type true.
Type assertions
There is a shorter way, and you will see it in every code base. as tells the compiler which type to use.
interface Book {
title: string;
copies: number;
}
const book = JSON.parse('{"title":"Dune","copyCount":3}') as Book;
const copies: number = book.copies;
console.log(copies);
undefined
as Book is a type assertion. It is a claim that you make, and nothing checks it. The compiler believes you, so book.copies has the type number. The server sent copyCount, so the value is undefined. A variable annotated as a number holds undefined, and nothing reported it.
The compiler refuses an assertion only when the two types have nothing in common.
const copies = "3" as number;
books.ts(1,16): error TS2352: Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
An assertion is acceptable when you really know more than the compiler does, for example right after a check that it cannot follow. It is a poor answer to a type error you have not read.
Comments that silence the compiler
Two comments switch off the error on the next line: // @ts-ignore and // @ts-expect-error. Prefer the second. It reports an error of its own when the next line has nothing to silence.
// @ts-expect-error The fee arrives as text.
const fee: number = 4;
fees.ts(1,1): error TS2578: Unused '@ts-expect-error' directive.
So the comment cannot stay in the code after the problem is fixed. You will see this comment in the practice exercises. It marks a call that must be refused, and it reports an error if your change makes that call valid.
The same lesson, six times
You have now seen code that compiles and goes wrong when it runs, in six shapes.
- Lecture 1: the types were right and the calculation was wrong.
- Lecture 6: an exclamation mark promised a value that was missing.
- Lecture 7: a list was read past its end.
- Lecture 9: a promise was thrown away, and the check read an old value.
- This lecture:
anylet a wrong field name through. - This lecture:
asclaimed a shape the data did not have.
Each time the cause is the same. A type is a statement about a value, and it is removed before the code runs. Where the compiler works the type out, the statement is reliable. Where you or a library tell it what to believe, it is only as true as what you told it. Data from outside the program is always in the second group.
A reviewer reads any, as and ! as three places where someone told the compiler what to believe. Expect a question on each one.
Remember this
any switches checking off and spreads to everything made from the value. unknown accepts everything and makes you check before use. as is a claim that nothing checks. For data from outside, such as a parsed response, check the value while the code runs.
Reference: any in the TypeScript Handbook.