Apologies in advance if I am incorrectly using the term, but I have a scenario where I can implement an interface in typescript that may not be entirely type safe. For instance:
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
Once again, I acknowledge that my explanation regarding "contravariance" might be inaccurate, but it seems perplexing that NamedPoint implements Point
would not be flagged by the compiler. I initially thought enabling strictFunctionTypes
in tsconfig would address this issue, but it seems ineffective in this case.
Is my comprehension of types flawed, or is there a discrepancy in TypeScript logic? If the latter is true, what actions can I take to rectify this?