【问题标题】:Optional class members in TypescriptTypescript 中的可选类成员
【发布时间】:2013-09-25 19:15:38
【问题描述】:

有没有办法在 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#,我正在寻找类似“字符串选项”的东西。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    以下在 TypeScript 3.x 中有效:

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

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

    【讨论】:

    • 有什么办法可以避免定义可选属性吗? ({a: 'asdf', b: 'nada' } 而不是 {a: 'asdf', b: 'nada', c: undefined }
    • 我也在 TypeScript Playground 和 VS 中得到 Supplied characters do not match any signature of call target see playground
    • 这个答案已经过时,或者至少宣传自 TypeScript 2.7 以来默认情况下不起作用的东西。
    • 这个答案已经过时,或者至少推广了自 TypeScript 2.7 以来默认情况下不起作用的东西。从 TS 2.7 开始,您将得到 Property 'c' has no initializer and is not definitely assigned in the constructor.,这是您的代码的正确答案,指出必须定义 Foo#c,但未安全初始化。
    • 答案已更新并适用于最新的 TypeScript 版本?
    【解决方案2】:

    Typescript 2.0 中添加了可选的类属性。

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

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

    Typescript 2.0 release notes - Optional class properties

    【讨论】:

    • 虽然这在理论上可以回答问题,it would be preferable 在此处包含答案的基本部分,并提供链接以供参考。
    • 根据您的反馈修改:)
    • 有趣。我正在使用 TS 4,如果我添加它会给我意外的令牌错误?在类定义中。界面似乎让它变得艰难。
    【解决方案3】:

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

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

    在 --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
    }
    

    Optional class properties

    【讨论】:

      【解决方案4】:

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

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

      playground

      【讨论】:

        猜你喜欢
        • 2017-01-21
        • 1970-01-01
        • 2018-06-07
        • 2016-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-04
        相关资源
        最近更新 更多