简体   繁体   English

打字稿界面上的可选参数?

[英]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: 这个界面的用处是:

  • On the implementer site, if any optional field is declared, the type must correspond (so phone has to be defined as number ) 在实现者站点上,如果声明了任何可选字段,则类型必须对应(因此phone必须定义为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. 在接收方(例如作为函数参数),您只能访问可能属于Person字段(您应检查它们是否undefined ),但该函数例如保证它不会访问Person参数的任何其他字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM