Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  122] [ 1]  / answers: 1 / hits: 47870  / 6 Years ago, sun, february 25, 2018, 12:00:00

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?


More From » angular

 Answers
19

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


[#55067] Wednesday, February 21, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
grayson

Total Points: 36
Total Questions: 113
Total Answers: 95

Location: Tonga
Member since Fri, Aug 21, 2020
4 Years ago
grayson questions
;