[英]Restrict accessing toString using typescript interface/type
I want to have an interface like this:我想要一个这样的界面:
export interface Point {
readonly x: number;
readonly y: number;
readonly toString: never;
}
I thought it will work like this:我认为它会像这样工作:
const p: Point = {x: 4, y: 5}; // OK
p.toString(); // triggers typescript error
However I get also this error on the first line:但是我在第一行也得到了这个错误:
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 an option to restrict usage of toString on some interface, without the need to write type assertions like const p: Point = {x: 4, y: 5} as Point;
是否有一个选项可以在某些接口上限制 toString 的使用,而无需编写类型断言,例如const p: Point = {x: 4, y: 5} as Point;
everywhere?到处?
My use case: I am currently rewriting what used to be我的用例:我目前正在重写以前的内容
class Point {
x: number;
y: number;
toString() {
return `${x} ${y}`;
}
}
to interfaced object with companion functions:将 object 与伴随功能接口:
interface Point {
x: number;
y: number;
}
function pointToString({x, y}: Point) {
return `${x} ${y}`;
}
and I want to make calls to point.toString()
in old codebase trigger an error, because they currently do not since every object in JS has a toString()
method.我想在旧代码库中调用point.toString()
会触发错误,因为它们目前没有,因为 JS 中的每个 object 都有一个toString()
方法。
I was able to get this working with the unknown
type:我能够使用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'.
I called it NullPrototype
because it's essentially the type-level version of this pattern in vanilla JS:我称它为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???
Here 'sa related issue on the TypeScript GitHub, though I don't think anyone's come up with this specific solution over there这是关于 TypeScript GitHub 的相关问题,尽管我认为那里没有人想出这个特定的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.