使用括号中的接口分配打字稿类型,括号的含义是什么?

时间:2020-01-05 17:04:17

标签: typescript interface declaration

我有这两个界面

export interface Contact {
  first_name: string;
  last_name: string;
  emails?: (EmailsEntity)[] | null;
  company: string;
  job_title: string;
}
export interface EmailsEntity {
  email: string;
  label: string;
}

用括号中的emails?: (EmailsEntity)[] | null;EmailsEntity分配是什么意思?

此表示法与emails?: EmailsEntity[] | null;有什么区别?

3 个答案:

答案 0 :(得分:1)

它实际上没有任何意义。在语法上,它与此类似:

emails?: EmailsEntity[] | null;

在这种情况下,不需要使用括号。仅在更改操作员的优先级时才需要。阅读有关operator precedence的更多信息,您可能会了解整个图片。

答案 1 :(得分:0)

(EmailsEntity)[]EmailsEntity[]之间没有区别。 Typescript允许(),因为使用某些类型运算符时,必须修改运算符的默认优先级。除非()是函数签名的一部分,否则它们在类型上没有任何其他含义。

答案 2 :(得分:0)

这里是example,括号很重要:

type MyUnion1 = { a: string } | EmailsEntity & { c: boolean }
// {a: string; } | { email: string; label: string; c: boolean; }

type MyUnion2 = ({ a: string } | EmailsEntity) & { c: boolean }
//              ^                            ^ 
// { a: string; c: boolean; } | { email: string; label: string; c: boolean; }

&(交集)运算符的优先级高于|(联合)。括号会更改优先级。