Typescript 中的可选类成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18916104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Optional class members in Typescript
提问by angularJsNewbie
Is there a way to specify type-safe optional members in Typescript classes?
有没有办法在 Typescript 类中指定类型安全的可选成员?
That is, something like...
也就是说,像...
class Foo {
a?: string;
b?: string;
c: number;
}
....
foo = new Foo();
...
if (foo.a !== undefined) { ... (access foo.a in a type-safe string manner) ... }
In case you are familiar with OCaml/F#, I am looking for something like 'string option'.
如果您熟悉 OCaml/F#,我正在寻找诸如“字符串选项”之类的东西。
采纳答案by basarat
The following works in TypeScript 3.x:
以下在 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).
请注意,您需要初始化任何非可选成员(如图所示或在构造函数中内联)。
回答by Fredrik_Macrobond
Optional class properties was added as a feature in Typescript 2.0.
可选的类属性作为 Typescript 2.0 中的一项功能添加。
In this example, property bis optional:
在本例中,属性b是可选的:
class Bar {
a: number;
b?: number;
}
回答by Distagon
In some use cases you can accomplish it with Parameter properties:
在某些用例中,您可以使用Parameter 属性来完成它:
class Test {
constructor(public a: string, public b: string, public c?: string)
{
}
}
var test = new Test('foo', 'bar');
回答by Mentor
Optional properties and methods can now be declared in classes, similar to what is already permitted in interfaces:
可选的属性和方法现在可以在类中声明,类似于接口中已经允许的:
class Bar {
a: number;
b?: number;
f() {
return 1;
}
g?(): number; // Body of optional method can be omitted
h?() {
return 2;
}
}
When compiled in --strictNullChecks mode, optional properties and methods automatically have undefined included in their type. Thus, the b property above is of type number | undefined and the g method above is of type (() => number) | undefined. Type guards can be used to strip away the undefined part of the type:
在 --strictNullChecks 模式下编译时,可选属性和方法会自动在其类型中包含 undefined 。因此,上面的 b 属性的类型为 number | undefined 并且上面的 g 方法是类型 (() => number) | 不明确的。类型保护可用于去除类型的未定义部分:
function test(x: Bar) {
x.a; // number
x.b; // number | undefined
x.f; // () => number
x.g; // (() => number) | undefined
let f1 = x.f(); // number
let g1 = x.g && x.g(); // number | undefined
let g2 = x.g ? x.g() : 0; // number
}