Typescript中的可选类成员

ang*_*bie 19 typescript

有没有办法在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范围的运行时库支持.

  • 有没有办法避免定义可选属性?(`{a:'asdf',b:'nada'}`而不是`{a:'asdf',b:'nada',c:undefined}` (4认同)
  • 这个答案已经过时了,或者至少宣传了自 TypeScript 2.7 以来默认不起作用的东西。从 TS 2.7 开始,您会得到 `Property 'c' 没有初始值设定项,并且没有在构造函数中明确分配。这是对您的代码的正确答案,该代码指出必须定义 `Foo#c` 但它不是安全初始化的。 (2认同)

小智 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)

Typescript 2.0发行说明-可选的类属性