简体   繁体   中英

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?

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.

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