typescript - 使用 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()
方法。
解决方案
推荐阅读
- reactjs - 尝试使用来自 node.js 服务器的 React useEffect 和 useState 加载图像的动态路径
- elasticsearch - Elasticsearch - Split string into common words without white space or special characters
- jenkins - 在 Jenkins 声明式管道中使用 imagePullSecrets
- blockchain - 智能合约 gas 成本
- python - Python 类在解析时出现意外的 EOF
- wpf - XAML 样式触发器 - 仅为具有特定名称的对象更改样式
- flutter - 如何在 Flutter 中创建侧边栏菜单,以便选择菜单会更改主面板小部件?
- node.js - 我可以安全地使用哪个分隔符来分隔节点中的 zlib 压缩字符串
- python - 如何检查 PYTHON 中不同位置的空命令行参数?
- c - 尝试添加到 C 中的链表开头时的无限循环