小编Jim*_*m U的帖子

Typescript 可以强制执行类类型吗?

在下面的示例中,我期望通过将变量声明c1为类型Coordinate,它将被初始化为实例Coordinate,否则会出现编译错误。

打字稿:

class Coordinate {
    x: number;
    y: number;

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

    toString(): string {
        return `(${this.x},${this.y})`;
    }
};

const c1 : Coordinate = {x:1, y:2};             // <=== problem
const c2 : Coordinate = new Coordinate(3, 4);

console.log('c1', c1 instanceof Coordinate ? 'Coordinate' : 'not Coordinate');
console.log('c2', c2 instanceof Coordinate ? 'Coordinate' : 'not Coordinate');

console.log(`c1: ${c1}`);
console.log(`c2: ${c2}`);
Run Code Online (Sandbox Code Playgroud)

汇编

官方节点typescript包转换此打字稿代码,没有错误或警告:

npx tsc …
Run Code Online (Sandbox Code Playgroud)

typescript

5
推荐指数
1
解决办法
308
查看次数

标签 统计

typescript ×1