Handbooks / TypeScript / Chapter 2
Interfaces, Types and Unions
7 pages · ~5 min✓ Reviewed
Builds on Basic Types. Next up: Narrowing.
Object Types Mental Model
1. Structural Typing
- A value fits if it has the required members; declared name or class is irrelevant
- Object type = required members + their types:
{ id: number; name: string } interfaceandtypeboth name a shape; one variable satisfies either
2. Assignability Is Directional
typescript
interface User { id: number; name: string } type Named = { name: string } const u: User = { id: 1, name: "Ann" } const n: Named = u // wider to narrower: OK const back: User = n // error: id missing
extra members are fine, missing ones are not
- Wider (extra members) is assignable to narrower
- Narrower to wider is an error: members missing
3. Runtime Reality
- Types are erased at compile time; no runtime check exists
- Validate external data separately
Remember
as User on parsed JSON checks nothing; it only silences the compiler.
Interfaces vs Type Aliases
1. Same Shape, Two Syntaxes
interface User { id: number }declares an object shapetype User = { id: number }does the same- interface:
interface Admin extends User { role: string } - alias:
type Admin = User & { role: string }(intersection)
2. What Only One Can Do
| interface | type |
|---|
Optional and Readonly Properties
1. Optional properties
nickname?: stringhas type string | undefined- The key may be omitted entirely
?is not the same as nullable
| Type | Key required? | undefined OK? |
|---|---|---|
{ a?: string } | no | yes |
{ a: string | undefined } |
Unions, Intersections and Literal Types
1. Unions and Intersections
| Value is | Access | |
|---|---|---|
A | B | one of A, B | common members only |
A & B | all of A and B | every member |
- Narrow with
typeof,in,instanceof,===iniforswitch
Structural Typing and Excess Property Checks
1. Structural Typing
- Identical structure ⇒ interchangeable
- A different name does not make types incompatible
typescript
type A = { id: number } interface B { id: number } const a: A = { id: 1 } const b: B = a // OK
2. Excess Property Checks
| Source | Code | Result |
|---|---|---|
| Fresh literal | const u: User = { id: 1, extra: 2 } |
Cheat Sheet: Object Types
1. Interface vs Type
| interface | type | |
|---|---|---|
| Extend | extends | & |
| Merge | yes, same name | error |
| Union, tuple, mapped | no | yes |
2. Properties and Unions
Check yourself
With type User = { id: number }, does const o = { id: 1, extra: 2 }; const u: User = o; compile?
- Yes, it compiles
- Excess property checks hit only fresh object literals
- Writing
{ id: 1, extra: 2 }directly in the assignment would error
Does const x: { a: string | undefined } = {}; compile?
- No, the key
ais still required - Only
a?: stringlets you omit the key