首页 文章

Typescript中的可选类成员

提问于
浏览
18

有没有办法在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) ... }

如果您熟悉OCaml / F#,我正在寻找类似'string option'的东西 .

4 回答

  • 12

    以下工作正常:

    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');
    }
    

    您甚至可以在创建时初始化:

    class Foo {
        a: string = 'asdf';
        b: string = 'nada';
        c: number;
    }
    
    var foo = new Foo();
    
    if (foo.c == undefined){
        console.log('c not defined');
    }
    

    需要注意的一点是,TypeScript类型会从生成的JavaScript中删除 . 因此,如果您正在寻找类似F# option 类型的内容,则需要运行时库支持,这超出了TypeScript的范围 .

  • 0

    在某些用例中,您可以使用Parameter properties完成它:

    class Test {
        constructor(public a: string, public b: string, public c?: string)
        {
        }
    }
    
    var test = new Test('foo', 'bar');
    

    playground

  • 5

    可选的类属性已添加为Typescript 2.0中的一项功能 .

    在此示例中,属性 b 是可选的:

    class Bar {
      a: number;
      b?: number;
    }
    

    Typescript 2.0 release notes - Optional class properties

  • 14

    现在可以在类中声明可选属性和方法,类似于接口中已允许的属性和方法:

    class Bar {
        a: number;
        b?: number;
        f() {
            return 1;
        }
        g?(): number;  // Body of optional method can be omitted
        h?() {
            return 2;
        }
    }
    

    在--strictNullChecks模式下编译时,可选属性和方法会自动在其类型中包含未定义 . 因此,上面的b属性是数字| undefined和上面的g方法是类型(()=>数字)|未定义 . 类型防护可用于去除类型的未定义部分:

    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
    }
    

    Optional class properties

相关问题