typescript - 类构造函数可选参数

标签 typescript

我希望能够初始化一个有或没有值的类。如果你传递一个值,那么一个类的所有方法都会期望这个值作为参数,并且该值将是你在初始化时传递的类型。
如果你什么都没传递,那么方法不会期望任何参数,并且值将是未定义的。
我认为代码会给出更好的例子:

class Foo<T = void> {
  constructor(public type?: T) {}

  bar = (type: T) => {
    if (type) {
      this.type = type;
    }
  };
}

const fooUndefined = new Foo();

fooUndefined.bar(); // no errors, this is ok
fooUndefined.type === undefined; // no errors, this is ok
fooUndefined.bar(1); // expected error, this is ok

const fooNumber = new Foo(0);

fooNumber.type === 1; // no errors, but type is `number | undefined`, this is not ok
fooNumber.type > 0; // unexpected error because type is `number | undefined`, this is not ok

fooNumber.bar(1); // no errors, this is ok
fooNumber.bar(); // expected error, need to pass number, this is ok
fooNumber.bar('1'); // expected error, strings are not acceptable, this is ok
所以type房产在fooNumber示例的类型为 number | undefined .有没有办法在没有显式类型转换的情况下将其缩小到数字?
Playground link

最佳答案

所有条件参数都得到 SomeType |不明确的。
你可以这样写绕过它。
转换到数字

fooNumber.type as number > 2
或者告诉 typescript 您确定使用 !表达。
fooNumber.type! > 2 

关于typescript - 类构造函数可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67094863/

相关文章:

node.js - 导出声明类型 ResourceType = Lowercase<Protocol.Network.ResourceType>,使用 Puppeteer 和 typescript 构建 nodejs 应用程序时出错

reactjs - 如何在 typescript 中为 API 数据创建接口(interface)?

angular - 类型脚本错误属性在类型上不存在

typescript - 如何让 TSLint 解决与 Yarn 工作区的间接类型依赖关系?

javascript - 将 RxJS 与 filter(Boolean) 一起用于查询?

javascript - 让 getStream(stream.io)在 Angular 应用程序中工作

typescript - 枚举不适用于 Nestjs 和 graphql

node.js - 如何从 Node 模块导出 Typescript 接口(interface)?

typescript - 类 'Subject<T>' 错误地扩展了基类 'Observable<T> Nativescript 抽屉导航错误

javascript - 为什么我的共享服务未在我的组件之间更新?