【发布时间】:2022-11-23 02:38:02
【问题描述】:
如果我滥用该术语,请先行道歉,但我能够在打字稿中实现一个我认为类型不安全的接口,例如:
interface Point {
x: number;
y: number;
dist (other: Point): number
}
GridPoint implements Point {
constructor (public x: number, public x: number) {}
dist (other: Point) { /* ... math here ... */ } //
}
NamedPoint implements Point {
// this class has an extra `name: string` property...
constructor (
public x: number,
public x: number,
public name: string
) {}
dist (other: NamedPoint) {
// other is a NamedPoint so other.name is okay, but this
// is not true of any Point, so how can NamedPoint be said
// to implement point?
if (other.name.startsWith()) { /* ... */ }
}
}
// this will throw if `a` is a NamedPoint and `b` is a GridPoint
function getDist (a: Point, b: point) {
console.log(`distance is: ${a.dist(b)}`)
}
// but tsc won't complain here:
getDist(new NamedPoint(1, 2, 'foo'), new GridPoint(9, 8));
link to full example on playground
同样,我确定我在“逆变”方面的措辞是错误的,但我认为 NamedPoint implements Point 会被编译器禁止。我以为我可以通过在 tsconfig 中打开 strictFunctionTypes 来获得它,但这显然不适用于这种情况。
是我对类型的理解不正确,还是这里的打字稿有误?如果是后者,我能做点什么吗?
【问题讨论】:
标签: typescript inheritance types interface contravariance