[英]Restrict accessing toString using typescript interface/type
我想要一个这样的界面:
export interface Point {
readonly x: number;
readonly y: number;
readonly toString: never;
}
我认为它会像这样工作:
const p: Point = {x: 4, y: 5}; // OK
p.toString(); // triggers typescript error
但是我在第一行也得到了这个错误:
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'.
是否有一个选项可以在某些接口上限制 toString 的使用,而无需编写类型断言,例如const p: Point = {x: 4, y: 5} as Point;
到处?
我的用例:我目前正在重写以前的内容
class Point {
x: number;
y: number;
toString() {
return `${x} ${y}`;
}
}
将 object 与伴随功能接口:
interface Point {
x: number;
y: number;
}
function pointToString({x, y}: Point) {
return `${x} ${y}`;
}
我想在旧代码库中调用point.toString()
会触发错误,因为它们目前没有,因为 JS 中的每个 object 都有一个toString()
方法。
我能够使用unknown
类型进行此操作:
type NullPrototype = Record<keyof Object, unknown>;
interface Point extends NullPrototype {
readonly x: number;
readonly y: number;
}
const p: Point = {x: 4, y: 5}; // OK
p.toString(); // TS error: Object is of type 'unknown'.
我称它为NullPrototype
是因为它本质上是 vanilla JS 中这种模式的类型级版本:
const p = Object.create(null); // TS infers type `any`
p.x = 4;
p.y = 5;
p.toString(); // Fails at runtime, but passes type check???
这是关于 TypeScript GitHub 的相关问题,尽管我认为那里没有人想出这个特定的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.