Sub topic 2
Object types with optional and readonly properties
This chapter assumes you know basic JavaScript objects and functions, and that you can run tsc with strict enabled.
Object types
An object type lists each property and its type. Adding ? makes a property optional, which gives it the type T | undefined. Adding readonly blocks reassignment after the object is created.
type User = {
readonly id: number;
name: string;
email?: string;
};
const u: User = { id: 1, name: "Ada" };
u.name = "Grace"; // ok
// u.id = 2; // Error: Cannot assign to 'id' because it is a read-only property.
const len = u.email?.length; // number | undefinedThe readonly modifier only applies at compile time and only one level deep. Nested objects stay mutable unless you mark them readonly too.
Function parameters and return values
TypeScript does not infer parameter types from how a function is called, so you have to annotate them. Without an annotation, a parameter becomes an implicit any, which strict mode reports as an error. TypeScript does infer return types, but on exported functions an explicit return type stops the public contract from drifting by accident.
function greet(user: User, loud = false): string {
const text = `Hello, ${user.name}`;
return loud ? text.toUpperCase() : text;
}A default value such as loud = false makes the parameter optional and lets TypeScript infer boolean for it.
null, undefined, and strictNullChecks
With strictNullChecks (part of strict), null and undefined are separate types. They are not valid values for every type. A value that may be missing has to say so in its type, and you have to check it before you use it.
function findUser(id: number): User | undefined {
return id === 1 ? { id: 1, name: "Ada" } : undefined;
}
const found = findUser(2);
// found.name; // Error: 'found' is possibly 'undefined'.
console.log(found?.name ?? "unknown");If you turn the flag off, every type silently accepts null and undefined, and the compiler can no longer catch the most common runtime crash.
Literal types and unions
A literal type is a single exact value, such as "GET" or 404. A union A | B accepts any of its members. Combining the two gives you a closed set of allowed values.
type Method = "GET" | "POST";
type Status = 200 | 404 | 500;
function request(method: Method, url: string): Status {
console.log(method, url);
return 200;
}
request("GET", "/users");
// request("PUT", "/users"); // Error: '"PUT"' is not assignable to type 'Method'.Exercise
Given type Opts = { readonly size?: number }, what is the type of opts.size, and can you write opts.size = 3?
Show answer
Its type is number | undefined because the property is optional. Assigning to it is a compile error because the property is readonly.
Exercise
Why does function f(x) { return x * 2; } fail under strict?
Show answer
The parameter x has no annotation, so it is implicitly any, and noImplicitAny reports that as an error. Annotate it, for example x: number.