Typescript可以强制类类型吗?
在下面的示例中,我希望通过将变量Typescript可以强制类类型吗?,typescript,Typescript,在下面的示例中,我希望通过将变量c1声明为typeCoordinate,它将被初始化为Coordinate的实例,或者我将得到一个编译错误 打字稿: 类坐标{ x:数字; y:数字; 构造函数(x:编号,y:编号){ 这个.x=x; 这个。y=y; } toString():字符串{ 返回`(${this.x},${this.y})`; } }; 常数c1:坐标={x:1,y:2};// 如前所述,Typescript在结构上是类型化的,因此一般来说,您需要考虑任何具有x或y的内容都是有效的坐标
c1
声明为typeCoordinate
,它将被初始化为Coordinate
的实例,或者我将得到一个编译错误
打字稿:
类坐标{
x:数字;
y:数字;
构造函数(x:编号,y:编号){
这个.x=x;
这个。y=y;
}
toString():字符串{
返回`(${this.x},${this.y})`;
}
};
常数c1:坐标={x:1,y:2};// 如前所述,Typescript在结构上是类型化的,因此一般来说,您需要考虑任何具有x
或y
的内容都是有效的坐标。不过,我们可以绕过这个问题。从
检查类实例的兼容性时,如果目标类型包含私有成员,则源类型还必须包含源自同一类的私有成员
所以如果我们给这个类一个私有成员(即使我们从未使用过它),就像这样
那么我们就不能直接使用坐标
来构造它
const c1 : Coordinate = {x:1, y:2}; // Error
const d1 : Coordinate = {_ignore: 0, x:1, y:2}; // Also an error
即使是d1
也会失败,因为尽管它具有所有正确的字段名,但私有字段名并不是来自正确的类。这使我们能够在需要时获得Java或Scala等语言的标称行为
注意:
如果您担心将字段添加到结构中,也可以使用私有成员函数执行相同的操作
class Coordinate {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
private _ignore(): void {}
toString(): string {
return `(${this.x},${this.y})`;
}
};
这也会产生同样的效果。TypeScript使用结构子类型,而不是名义子类型,因此我认为这是不可能的,但如果能听到权威性的答案,那就太好了。另请参见:这很有效,谢谢!使用私有成员函数而不是数据成员会避免增加数据结构的大小吗?例如:private_ignore():void{}代码>非常好。我没想到。私有成员函数应该以更少的空间成本具有相同的效果。
c1 Coordinate
c2 Coordinate
c1: (1,2)
c2: (3,4)
class Coordinate {
private _ignore: any;
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}; // Error
const d1 : Coordinate = {_ignore: 0, x:1, y:2}; // Also an error
class Coordinate {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
private _ignore(): void {}
toString(): string {
return `(${this.x},${this.y})`;
}
};