Here's the interface I'm aiming for:
export interface Point {
readonly x: number;
readonly y: number;
readonly toString: never;
}
I initially expected it to function this way:
const p: Point = {x: 4, y: 5}; // This should work fine
p.toString(); // Should trigger a typescript error
However, I encountered an error on the first line as well:
TS2322: Type '{ x: number; y: number; }' is not assignable to type 'Point'.
Types of property 'toString' are incompatible.
Type '() => string' is not assignable to type 'never'.
Is there a way to restrict the usage of toString within an interface without resorting to using type assertions like
all over the place?const p: Point = {x: 4, y: 5} as Point;
In my current scenario, I am in the process of converting what was originally
class Point {
x: number;
y: number;
toString() {
return `${x} ${y}`;
}
}
to objects defined by interfaces with helper functions:
interface Point {
x: number;
y: number;
}
function pointToString({x, y}: Point) {
return `${x} ${y}`;
}
and I want attempts to call point.toString()
in legacy code to throw an error, something that does not currently happen due to JavaScript objects having a default toString()
method.