[英]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? Customer
现在是否正确实现了Person,因为Person
接口上的所有属性都是可选的?
The short answer is yes, Customer
correctly implements Person
since all fields of the interface are optional any object will correctly implement the interface. 简短的回答是肯定的, Customer
正确实现Person
因为接口的所有字段都是可选的,任何对象都将正确地实现接口。
The usefulness of this interface is: 这个界面的用处是:
phone
has to be defined as number
) 在实现者站点上,如果声明了任何可选字段,则类型必须对应(因此phone
必须定义为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. 在接收方(例如作为函数参数),您只能访问可能属于Person
字段(您应检查它们是否undefined
),但该函数例如保证它不会访问Person
参数的任何其他字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.