TypeScript 学习笔记 01: TypeScript for JavaScript Programmers

Code snippets coming from TypeScript for JavaScript Programmers

console.clear()
console.log(Date())

let helloWorld = "Hello World"
let age = 23

// 定义接口时,属性值之间不是用逗号分隔,而是用分号分隔,分号也可省略
interface User {
    name: string
    id: number
}
const user: User = {
    name: 'Hades',
    id: 0,
}

// 在类中也可以声明接口
class UserAccount {
    name: string
    id: number

    constructor(name: string, id: number) {
        this.name = name
        this.id = id
    }
}

// User 接口和 UserAccount 类的属性值相同
const user2: User = new UserAccount('Murphy', 1)

// 定义函数的入参类型和返回值类型
function getAdminUser(): User {
    return user
}

function deleteUser(user: User) {}

// 枚举类型的值数量很少时,可直接用值来定义,| 符号为 Union 方式的组合类型
type MyBool = true | false
type WindowStates = 'open' | 'closed' | 'minimized'
type LockStates = 'locked' | 'unlocked'
type PositiveOddNumbersUnderTen = 1 | 3 | 5 | 7 | 9

// 函数入参及返回值也可用 Union 定义组合类型
function getLength(obj: string | string[]): number {
    return obj.length
}

function wrapInArray(obj: string | string[]) {
    if (typeof obj === 'string') {
        return[obj]
    }
    return obj
}

// 泛型
type StringArray = Array<string>
type NumberArray = Array<number>
type ObjectWithNameArray = Array<{ name: string }>

// 更复杂的泛型
// TODO: 68行被注释的代码,实际执行会报错,找出原因
interface Backpack<Type> {
    add: (obj: Type) => void
    get: () => Type
}

// declare const backpack: Backpack<string>
// const object = backpack.get()
// backpack.add(23)

interface Point {
    x: number
    y: number
}

function logPoint(p: Point) {
    console.log(`${p.x}, ${p.y}`)
}

// duck-typing: point 对象与 Point 这个接口的 shape 相同,即视为同一类型
const point = {
    x: 12,
    y: 16,
}
logPoint(point)

const point3 = { x: 12, y: 26, z: 89 }
logPoint(point3)

// 并不要求与 Point 接口的属性值个数完全相同,多一些是没问题的,但是少了肯定不行
const rect = { x: 33, y: 3, width: 30, height: 80 }
logPoint(rect)

// const color = { hex: '#187abf' }
// logPoint(color)

// 类和对象都可以享受 duck-typing
class VirtualPoint {
    x: number
    y: number

    constructor(x: number, y: number) {
        this.x = x
        this.y = y
    }
}

const newPoint = new VirtualPoint(13, 56)
logPoint(newPoint)

Powered by Sairin