Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameters on typescript interfaces?

As explained here the ? operator can be used to mark a function parameter as optional. What does the ? operator mean on interface parameters? For example if we have this typescript interface:

    export interface Person {
    phone?: number;
    name?: string;
}

And a class that implements the interface:

class Customer implements Person {
} 

Did Customer now implement Person correctly because all the properties on the Person interface are optional?

like image 645
Ole Avatar asked Feb 25 '18 18:02

Ole


People also ask

How do you pass optional parameters in TypeScript?

In Typescript, making optional parameters is done by appending the “?” at the end of the parameter name in the function when declaring the parameters and the parameters which are not marked with “?” i.e not optional parameter are called as default parameters or normal parameters where it is must and compulsory to pass ...

Does TypeScript support optional parameters?

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.

How do I make my properties optional in TypeScript interface?

To make a single property in a type optional, create a utility type that takes a type and the property name as parameters and constructs a new type with the specific property marked as optional. Copied!

Can we have interface with optional and default properties in TypeScript?

If you want to set the properties of an interface to have a default value of undefined , you can simply make the properties optional. Copied!


1 Answers

The short answer is yes, Customer correctly implements Person since all fields of the interface are optional any object will correctly implement the interface.

The usefulness of this interface is:

  • On the implementer site, if any optional field is declared, the type must correspond (so phone has to be defined as number)
  • On receiving side (for example as a function parameter) you can only access fields that are potentially part of Person (you should check if they are undefined) but the function for example guarantees it will not access any other fields of a Person parameter.
like image 96
Titian Cernicova-Dragomir Avatar answered Sep 29 '22 18:09

Titian Cernicova-Dragomir