简体   繁体   中英

Optional class members in Typescript

Is there a way to specify type-safe optional members in Typescript classes?

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'.

The following works in 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).

Optional class properties was added as a feature in Typescript 2.0.

In this example, property b is optional:

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

Typescript 2.0 release notes - Optional class properties

In some use cases you can accomplish it with Parameter properties :

class Test {
    constructor(public a: string, public b: string, public c?: string)
    {
    }
}

var test = new Test('foo', 'bar');

playground

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM