STAGE 02 / LESSON 01
TypeScript: types and narrowing
TypeScript checks assumptions about JavaScript data before the code runs.
THE IDEA
Understand it.
A type describes the shape of a value. A union such as 'open' | 'done' limits the values accepted by the type checker. Types are removed when TypeScript is compiled; they do not validate untrusted input at runtime.
Narrowing uses a check, such as typeof or a discriminant, to make a type more specific. Validate data received from a network or form at a trusted boundary before treating it as a known type.
SEE IT IN CONTEXT
Describe a task
type Task = {
id: string;
title: string;
status: "open" | "done";
};
function label(task: Task): string {
return task.status === "done" ? "Complete" : "Open";
}A misspelled status is caught during type checking, but an API can still return invalid data unless the response is validated.
LEARN FROM REAL WEBSITES
See it in the real world.
These simplified structures come from public sources. Company systems change, and the sources may describe only one project or an earlier design.
Spotify
Spotify engineering, 2021TypeScript across client platforms
Spotify reported rewriting its shared web and desktop client in TypeScript and defining platform APIs.
- React interface
- Typed platform API
- Web or desktop capabilities
What to learn: Types can describe a boundary used by different clients. The report describes the architecture in 2021.
Read the source: Spotify desktop and web architectureSlack
Slack engineering, 2017Introducing TypeScript
Slack's engineering team described adopting TypeScript to make a large JavaScript application easier to develop and maintain.
- Application code
- Type checking
- JavaScript output
What to learn: Type checking can catch mismatched assumptions before release, while runtime data still needs validation.
Read the source: TypeScript at SlackTRY IT YOURSELF
Practice.
Why is JSON.parse(responseText) not guaranteed to be a valid Task?
Show one possible answer
External JSON is runtime data and TypeScript types are erased. Check its structure and values before relying on the Task type.
GO DEEPER