首页 > 解决方案 > 使用 typescript 接口/类型限制访问 toString

问题描述

我想要一个这样的界面:

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}`;
    }
}

与伴随函数的接口对象:

interface Point {
    x: number;
    y: number;
}
function pointToString({x, y}: Point) {
    return `${x} ${y}`;
}

我想point.toString()在旧代码库中调用会触发错误,因为它们目前没有,因为 JS 中的每个对象都有一个toString()方法。

标签: typescript

解决方案


推荐阅读