You are on page 1of 1

Item 7: Think of Types as Sets of Values

- never as the empty set


- unknown as the universal set
type K = keyof (Person | Lifespan); // Type is never -> there are no keys
that belong to a value in the union type
keyof (A&B) = (keyof A) | (keyof B)
keyof (A|B) = (keyof A) & (keyof B)
extends means "assignable to" or "subset of"

Item 8
- use a type declaration instead of a type assertion in map
const people = ['alice', 'bob', 'jan'].map(
(name): Person => ({name})
); // Type is Person[]

X as unknown as Y - convert any type X to any other type Y

Chapter 4: Type Design

Item 28: Types should model only valid states, even at the cost of verboseness
Item 29: Be Liberal in What You Accept and Strict in What You Produce

Tagged/discriminated union: e.g. one of the properties is a union of literal types,


so in the code we can check for that type to determine the whole object type.

Avoid “stringly typed” code. Prefer more appropriate types where not every string
is a possibility
Prefer keyof T to string for function parameters that are expected to be properties
of an object

Chapter 5:

Item 38: Use the Narrowest Possible Scope for any Types
- example: as any in a function call instead of variable declaration

- use unknown whenever the user knows more about the output of a function, and can
assign a type to the return value

You might also like