DAY 5 OF 30
Object types, optional and readonly
Yesterday, in one sentence
A type that says a value can be one of several types, written with | between
them.
Did you say:
- ✓a value can be one of several types
- ✓written with `|` between them
Interview question
string | boolean[], (string | boolean)[] and [boolean, string]?The first is a string, or an array of booleans. The second is an array where each value can be a string or a boolean, with no fixed length. The third is a tuple type with exactly two values, a boolean then a string.
Did you say:
- ✓brackets change what the union applies to
- ✓`(string | boolean)[]` is any length
- ✓`[boolean, string]` is fixed length and order
You add a type annotationType Annotation to an object by listing its property names and their types inside braces. It looks just like a JavaScript object, but with types instead of values. This is called an object type, and it describes the shape the object must have.
let user: { id: number; name: string } = { id: 1, name: "Sam" };
user.name = "Alex"; // ok
user.name = 5; // ❌ Type 'number' is not assignable to type 'string'
user.email = "a@b.com"; // ❌ Property 'email' does not exist on this type
Adding a ? to a property name in an object type makes it an optional property,
so the object does not have to include it. Reading an optional property gives you a union typeUnion Type of the declared type and undefined,
because the property might not be there.
let user: { id: number; nickname?: string } = { id: 1 };
user.nickname; // string | undefined
Putting readonly in front of a property name in an object type stops that property
being reassigned after the object is created.
let user: { readonly id: number; name: string } = { id: 1, name: "Sam" };
user.name = "Alex"; // ok
user.id = 2; // ❌ Cannot assign to 'id' because it is a read-only property
You might be wondering how readonly differs from const.
const stops the variable being reassigned. readonly stops a property inside the
object being reassigned. They protect different things, and you can use both
together.
Check yourself
let user: { id: number; nickname?: string }, what is the type of
user.nickname?The ? means the property may be absent, so reading it gives the declared type or undefined. It does not allow null.
? do to a property in an object type, and what does readonly do?? makes it an optional property, so reading it gives the type or undefined.
readonly stops the property being reassigned after the object is created.
Did you say:
- ✓`?` makes it an optional property
- ✓reading it gives the type or `undefined`
- ✓`readonly` stops the property being reassigned