Typescript 中的可选类成员 [英] Optional class members in Typescript

查看:53
本文介绍了Typescript 中的可选类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Typescript 类中指定类型安全的可选成员?

Is there a way to specify type-safe optional members in Typescript classes?

也就是说,像……

class Foo {
    a?: string;
    b?: string;
    c: number;
}

....

foo = new Foo();
...
if (foo.a !== undefined) { ... (access foo.a in a type-safe string manner) ... }

如果您熟悉 OCaml/F#,我正在寻找诸如字符串选项"之类的东西.

In case you are familiar with OCaml/F#, I am looking for something like 'string option'.

推荐答案

以下在 TypeScript 3.x 中有效:

The following works in TypeScript 3.x:

class Foo {
  a?: string;
  b?: string;
  c: number = 123;
}

请注意,您需要初始化任何非可选成员(如所示的内联成员或构造函数中的成员).

Note that you need to initialise any members that are not optional (either inline as shown or in the constructor).

这篇关于Typescript 中的可选类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆