TypeScript
Types
Basic Types
- Primitive
type A = number
type B = string
type C = boolean
type D = undefined
type E = null
- Array
// single-type
type A = number[]
type B = Array<number>
// multi-types
type C = (number | string)[]
type D = Array<number | string>
- Object
type A = {
x: number;
y?: number; // Optional Property
}
- Function
type A = () => void
type B = (x: number) => number
type C = (x?: number) => number // Optional Parameter
type D = (x: number, ...rest: number[]) => void // Rest Parameters
- never
// empty set
function fn(x: number) {
if (typeof x === 'number') { }
else { } // x: never
}
// function never return
function fn(): never { // fn: () => never
throw new Error()
}
- Any & Unkonwn
function fn(x: any) {
x() // ✅
x.a() // ✅
}
function fn(x: unknown) {
x() // ❌
x.a() // ❌
}
Collection Types
- Union
type A = 1 | 2 | 3
type B = number | string
- Intersection
type A = number | boolean
type B = number | string
type C = A & B // number
Type Inference
Variable Assignment
let A = 100 // number
let B = condition ? 100 : 'hi' // string | number
B = 100
console.log(B) // number
B = 'hi'
console.log(B) // string
Operator
- equality
function fn(x: number | null | undefined) {
if (typeof x === 'number') { } // x: number
if (x === null) { } // x: null
if (x == null) { } // x: null | undefined
if (x != null) { } // x: number
}
function fn(x: number | string, y: number | boolean) {
if (x === y) { } // x: number
}
- in
type Dog = { name: string, bark: () => string }
type Cat = { name: string, meow: () => string }
function fn(x: Dog | Cat) {
if ('name' in x) { } // x: Dog | Cat
if ('bark' in x) { } // x: Dog
}
- instanceof
function fn(x: number[] | number) {
if (x instanceof Array) { } // x: number[]
}
Control Flow
- if-else
function fn(x: number | string) {
if (typeof x === 'number') {
// x: number
} else {
// x: string
}
}
- switch
function fn(x: number | string) {
switch (typeof x) {
case 'number': break // x: number
case 'string': break // x: string
}
}