在下面的示例中,我期望通过将变量声明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 ×1