我有一个用例,我想在方法被调用后从类方法的返回类型中排除方法。即,让我们假设我有一个班级
Setup
有方法step1
,step2
和step3
class Setup {
step1() {
return this;
}
step2() {
return this;
}
step3() {
return this;
}
}
let setup = new Setup();
我的用例是,一旦调用 step1,它应该返回一个根本没有
step1
方法的 Setup 实例,并且用户应该只能获得在 step2
和 step3
之间进行选择的选项,一旦 step2
是调用它应该只会得到step3
,因为step1
和step2
已经被调用了。
let setup = new Setup();
setup
.step1()
.step2()
.step1(); // This should not be possible as step 1 was already invoked
我已经尝试过这个,但是在调用
step2
之后它再次显示step1
作为一个选项。我知道这部分是由于 Omit 将 Setup
作为它应该从中排除密钥的类型。但是,我无法找到一种方法来引用当前实例并排除当前方法。
export type Omit<A extends object, K extends string> = Pick<A, Exclude<keyof A, K>>
class Setup {
step1(): Omit<Setup, 'step1'> {
return this;
}
step2(): Omit<Setup, 'step2'>{
return this;
}
step3():Omit<Setup, 'step3'>{
return this;
}
}
let setup = new Setup();
除了让它与 Typescript 一起工作之外,应该注意它不应该是唯一的执行者并且可以很容易地被规避。
通过确保一旦
step1
被调用,对它的其余调用将被忽略,您可以变得更加健壮。
这样,您实际上可以确保实现您的意图,而不仅仅是通过 Typescript 的类型系统进行修补。
为此,有一个标志,一旦
step1
被调用,下一次,如果它是真的,不要在 step1
中做任何事情。
class Setup {
#usedStep1 = false;
step1() {
if (!this.#usedStep1) {
console.log("Used Step 1");
this.#usedStep1 = true;
}
return this;
}
step2() {
return this;
}
step3() {
return this;
}
}
let setup = new Setup();
现在,
setup
.step1() // Actually runs, you can see console log
.step2()
.step1() // Doesn't run