孙亖 avatar

TypeScript中的可选属性和只读属性

sunsi

Published: 23 Jan 2018 › Updated: 23 Jan 2018TypeScript中的可选属性和只读属性

TypeScript中的可选属性和只读属性

  • 可选属性

接口里的属性不全都是必需的。 有些是只在某些条件下存在,或者根本不存在。 例如给函数传入的参数对象中只有部分属性赋值了。带有可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个?符号。如下所示:

interface Person {
  name: string;
  age?: number;
  gender?: number;
}

上面的例子中Person对象名字(name)是不可选的,age和gender是可选的。

  • 只读属性

顾名思义就是这个属性是不可写的,对象属性只能在对象刚刚创建的时候修改其值。 你可以在属性名前用 readonly来指定只读属性,如下所示:

interface User {
    readonly loginName: string;
    password: string;
}

上面的例子说明,当完成User对象的初始化后loginName就不可以修改了。

  • readonly vs const

最简单判断该用readonly还是const的方法是看要把它做为变量使用还是做为一个属性。 做为变量使用的话用const,若做为属性则使用readonly

TypeScript快速入门.jpg

如何用Python爬取网页制作电子书.jpg

请点击阅读原文,查看原文博客。

阅读原文

Leave TypeScript中的可选属性和只读属性 to:

Written by

Read more #typescript posts


Best Posts From 孙亖

We have not curated any of sunsi's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From 孙亖