有没有办法在Typescript类中指定类型安全的可选成员?
就是这样......
class Foo {
a?: string;
b?: string;
c: number;
}
....
foo = new Foo();
...
if (foo.a !== undefined) { ... (access foo.a in a type-safe string manner) ... }
Run Code Online (Sandbox Code Playgroud)
如果您熟悉OCaml/F#,我正在寻找类似'string option'的东西.
bas*_*rat 16
以下工作正常:
class Foo {
a: string;
b: string;
c: number;
}
var foo = new Foo();
foo.a = "asdf";
foo.b = "nada";
if (foo.c == undefined){
console.log('c not defined');
}
Run Code Online (Sandbox Code Playgroud)
您甚至可以在创建时初始化:
class Foo {
a: string = 'asdf';
b: string = 'nada';
c: number;
}
var foo = new Foo();
if (foo.c == undefined){
console.log('c not defined');
}
Run Code Online (Sandbox Code Playgroud)
需要注意的一点是,TypeScript类型会从生成的JavaScript中删除.因此,如果您正在寻找类似F#option
类型的东西,您将需要一个超出TypeScript范围的运行时库支持.
小智 12
在某些用例中,您可以使用Parameter属性完成它:
class Test {
constructor(public a: string, public b: string, public c?: string)
{
}
}
var test = new Test('foo', 'bar');
Run Code Online (Sandbox Code Playgroud)
Fre*_*ond 11
可选的类属性已添加为Typescript 2.0中的功能。
在此示例中,属性b是可选的:
class Bar {
a: number;
b?: number;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
24006 次 |
最近记录: |