为什么说 TypeScript 是类型系统最强大的语言?

就说 2 点就没有任何语言可以做到:

1. Union Type / Intersection Type 这样动态带逻辑关系的类型。

interface BaseShape {
    name: string;
    pos: { x: number, y: number }
}

interface Circle {
    type: 'Circle',
    radius: number
}

interface Rect {
    type: 'Rect',
    width: number,
    height: number
}

interface Line {
    type: 'Line',
    to: { x: number, y: number },
    width: number
}

type Shape = BaseShape & ( Circle | Rect | Line )

2. 控制流分析,即根据代码上下文自动推断实际类型。

type Result = {
    isSucc: true,
    result: { value: string }
} | {
    isSucc: false,
    errMsg: string
}

function test(res: Result) {
    if (res.isSucc) {
        // 编译通过
        console.log(res.result);
    }

    // 编译报错
    console.log(res.result);
}

猜你喜欢

转载自blog.csdn.net/weixin_56356934/article/details/140313191