typescript - 强制要调用的方法
问题描述
我有一些构建器类实现了预期构建的接口。
但我想让这个类的一种方法需要调用。要求是指编译时,而不是运行时检查。
类应该用作方法调用链,然后作为它实现的接口传递给函数。最好在构造函数之后要求方法,但这并不是真正需要的。
示例:操场
interface ISmth {
x: number;
y?: string[];
z?: string[];
}
class SmthBuilder implements ISmth {
x: number;
y?: string[];
z?: string[];
constructor(x: number) {
this.x = x;
}
useY(y: string) {
(this.y = this.y || []).push(y)
return this
}
useZ(z: string) {
(this.z = this.z || []).push(z)
return this
}
}
declare function f(smth: ISmth): void
f(new SmthBuilder(123)
.useY("abc") // make this call required
.useZ("xyz")
.useZ("qwe")
)
解决方案
我的倾向是扩展ISmth
以表示useY()
已被调用,如下所示:
interface ISmthAfterUseY extends ISmth {
y: [string, ...string[]];
}
然后你SmthBuilder
的useY()
方法可以返回一个ISmthAfterUseY
:
useY(y: string) {
(this.y = this.y || []).push(y)
return this as (this & ISmthAfterUseY);
}
并且您的f()
函数,如果它关心获得ISmth
具有已定义的非空 y
属性的 a ,则应该要求 anISmthAfterUseY
而不是 a ISmth
:
declare function f(smth: ISmthAfterUseY): void
f(new SmthBuilder(123)
.useY("abc")
.useZ("xyz")
.useZ("qwe")
) // okay
f(new SmthBuilder(123).useZ("xyz")) // error!
// Types of property 'y' are incompatible.
好的,希望有帮助;祝你好运!
推荐阅读
- python-3.x - 为什么 1/2*2 在 Python 中是 1 而不是 0.25,因为 python 遵循 PEDMAS?
- c++ - 关于“使用命名空间标准”的问题?
- python - 如何使用类中的方法来比较该类的两个对象
- javascript - 猫鼬模式无法读取未定义的属性“密码”
- php - 删除换行符和空格 php
- css - 为什么伪元素背景颜色与变换一起使用时会覆盖其父背景颜色?
- dwarf - DW_AT 代码 0x05 是什么?在 DWARF 标准中找不到
- html - 遇到浮动内容时,粘性导航会中断?
- javascript - 是否可以使用 javascript/python 从 libVLC 获取音轨数据
- c++ - 指向 C++ 中指针向量的指针