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'.
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? 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 .
In TypeScript, we cannot define multiple constructors like other programming languages because it does not support multiple constructors.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With