首页 > 解决方案 > 强制要调用的方法

问题描述

我有一些构建器类实现了预期构建的接口。

但我想让这个类的一种方法需要调用。要求是指编译时,而不是运行时检查。

类应该用作方法调用链,然后作为它实现的接口传递给函数。最好在构造函数之后要求方法,但这并不是真正需要的。

示例:操场

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")
)

标签: typescript

解决方案


我的倾向是扩展ISmth以表示useY()已被调用,如下所示:

interface ISmthAfterUseY extends ISmth {
  y: [string, ...string[]];
}

然后你SmthBuilderuseY()方法可以返回一个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.

好的,希望有帮助;祝你好运!

游乐场链接


推荐阅读