Live Note

Remain optimistic

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 »

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 »

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 »

在 TypeScript 的类型系统中,逆变(Contravariance)协变(Covariance)双变(Bivariance)不变(Invariance) 是描述类型兼容性和子类型关系的重要概念。这些术语来源于类型理论,主要用于处理函数类型、泛型和接口的赋值规则。理解这些概念不仅能帮助我们编写更安全的代码,还能让我们更好地设计类型系统。本文将逐一讲解这四种变型,辅以代码示例,让你轻松掌握它们的含义与应用。

Read more »