Live Note

Remain optimistic

Numeric enums

1
2
3
4
5
6
7
8
9
10
11
12
enum Direction {
UP,
DOWN,
LEFT,
RIGHT,
}

function move(length: number, direction: Direction): void {
console.log(`move: ${direction} ${length}meters.`)
}

move(10, Direction.UP)

String enums

1
2
3
4
5
6
enum Direction {
UP = "UP",
DOWN = "DOWN",
LEFT = "LEFT",
RIGHT = "RIGHT",
}
Read more »

Generics

1
2
3
4
5
6
7
8
function foo<T>(arg: T): T {
return arg
}

function len<T>(arg: Array<T>): Array<T> {
console.log(arg.length)
return arg
}

Generics Types

1
2
3
4
5
6
7
8
9
10
11
function foo<T>(arg: T): T {
return arg
}

interface fooInterface<T> {
(arg: T): T
}

let myFunction: <T>(arg: T) => T = foo
let otherFunction: { <T>(arg: T): T } = foo
let interfaceFunction: fooInterface<number> = foo
Read more »

Function Types

Typing the function

1
2
3
4
5
6
7
function foo(x: number, y: string): string {
return x + y
}

let fo = function (x: number, y: string): string {
return x + y
}

Writing the function type

1
2
3
4
5
6
let foo: (x: number, y: string) => string = function (
x: number,
y: string
): string {
return x + y
}

Inferring types

1
2
3
let foo: (x: number, y: string) => string = function (x, y) {
return x + y
}
Read more »

Interface

1
2
3
4
5
6
7
8
9
10
interface labelValue {
label: string
}

function printLabel(obj: labelValue): void {
console.log(obj.label)
}

let obj = { size: 10, label: "some text" }
printLabel(obj)

Optional Properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface SquareConfig {
color?: string
width?: number
}

function createSquare(config: SquareConfig): { color: string; area: number } {
let defaultSquare = { color: "White", area: 200 }
if (config.color) defaultSquare.color = config.color
if (config.width) defaultSquare.area = config.width ** 2

return defaultSquare
}

console.log(createSquare({ color: "Black", width: 30 }))

Readonly Properties

1
2
3
4
5
6
7
interface Point {
readonly x: number
readonly y: number
}

let readOnlyArray: ReadonlyArray<number> = [1, 2, 3, 4]
let a: number[] = readOnlyArray as number[] // readonly array assignment to ordinary array

Excess Property Checks

1
2
3
4
5
6
7
interface SquareConfig {
color?: string
width?: number
[propName: string]: any
}

let newSquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig)
Read more »

Introduction

1
2
3
4
5
6
7
8
9
interface A {
text: string
}

class B {
text: string
}

let a: A = new B() // no error

At least same member

1
2
3
4
5
6
7
8
9
10
11
interface A {
text: string
}

function foo(obj: { text: string }): string {
return obj.text
}

let obj = { text: "some text", num: 3 }
let a: A = obj // success
foo(obj) // success
Read more »