angularJsNewbie angularJsNewbie - 1 month ago 8
TypeScript Question

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

Answer

The following just works:

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

You can even initialize on creation :

class Foo {
    a: string = 'asdf';
    b: string = 'nada';
    c: number;
}

var foo = new Foo();

if (foo.c == undefined){
    console.log('c not defined');
} 

One thing to note is that TypeScript types are erased from the generated JavaScript. So if you are looking for something like F# option type you will need a runtime library support which is beyond the scope of TypeScript.