Sub topic 2
Static Types in Practice
This chapter assumes you know JavaScript functions, objects, and modules. You should also be comfortable using a terminal and reading package.json. The examples use TypeScript syntax, but the same ideas apply to most statically typed languages.
What a static type does
A type describes the kind of value a variable can contain. For example, string describes text, number describes numeric values, and boolean describes true or false.
Static typing means that a tool checks these descriptions before the program runs. TypeScript checks your source code during development. It can report that a function receives the wrong kind of argument or that a property does not exist on an object.
function greet(name: string): string {
return `Hello, ${name}!`;
}
const message = greet("Ada");
console.log(message);The name: string annotation says that greet expects text. The ): string annotation says that the function returns text. TypeScript can infer some types without annotations:
const count = 3; // inferred as number
const language = "TS"; // inferred as stringInference is useful because you do not need to annotate every value. Add annotations where they clarify a function's contract, protect data at a boundary, or prevent an important mistake.
Errors caught before runtime
Consider this call:
function formatPrice(amount: number): string {
return `$${amount.toFixed(2)}`;
}
console.log(formatPrice(19.99));
// console.log(formatPrice("19.99")); // Error: string is not assignable to numberJavaScript would allow the second call to start running. It would then fail when "19.99" does not have the expected numeric behavior. TypeScript reports the mismatch while you are editing or compiling the file.
Types also describe object shapes. An object shape is the set of properties an object has and the types of those properties.
type User = {
id: number;
name: string;
email?: string;
};
function displayUser(user: User): string {
const contact = user.email ?? "no email";
return `${user.name} (${contact})`;
}
console.log(displayUser({ id: 1, name: "Ada" }));The ? marks email as optional. The ?? operator supplies a fallback when that property is missing or undefined.
| TypeScript feature | What it checks |
|---|---|
| `string`, `number`, `boolean` | Primitive values |
| Function parameter types | Arguments passed to a function |
| Object types | Required and optional properties |
| Return types | Values produced by a function |
Types describe code, but do not validate data
TypeScript checks your code at compile time. It does not automatically inspect data received from a network request, file, or user. External data can still be wrong at runtime.
type Settings = {
theme: "light" | "dark";
};
function saveSettings(settings: Settings): void {
console.log(`Saving ${settings.theme} mode`);
}
const rawData: unknown = JSON.parse('{"theme":"dark"}');
if (
typeof rawData === "object" &&
rawData !== null &&
"theme" in rawData &&
(rawData.theme === "light" || rawData.theme === "dark")
) {
saveSettings(rawData as Settings);
}unknown means that the value must be checked before it is used. This is safer than any, which disables most type checking for that value.
Following a value through a program
TypeScript narrows a type when your code checks it. A union type lists more than one possible type.
function describe(value: string | number): string {
if (typeof value === "string") {
return `Text with ${value.length} characters`;
}
return `Number: ${value.toFixed(2)}`;
}
console.log(describe("hello"));
console.log(describe(12));Inside the if block, TypeScript knows that value is a string. After the check, it knows that value is a number. This lets you handle each case without unsafe assumptions.
Exercise
What problem does the type unknown solve when reading JSON data?
Show answer
It prevents the program from using the data as if its shape were already known. Code must first check or validate the value before treating it as a specific type.