Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional class members in Typescript

Tags:

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

like image 358
angularJsNewbie Avatar asked Sep 20 '13 11:09

angularJsNewbie


People also ask

Does TypeScript have optional?

TypeScript provides a Optional parameters feature. By using Optional parameters featuers, we can declare some paramters in the function optional, so that client need not required to pass value to optional parameters.

What does ?: Mean in TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

Can TypeScript have multiple constructors?

In TypeScript, we cannot define multiple constructors like other programming languages because it does not support multiple constructors.

Should you use classes in TypeScript?

When should we use classes and interfaces? If you want to create and pass a type-checked class object, you should use TypeScript classes. If you need to work without creating an object, an interface is best for you.


1 Answers

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

like image 193
basarat Avatar answered Sep 20 '22 11:09

basarat