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?
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 ...
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.
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!
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!
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:
phone
has to be defined as number
)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.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