Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2927c9f

Browse files
authored
add instructions for propName
为任意属性添加一个例子
1 parent 2eb4050 commit 2927c9f

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

basics/type-of-object-interfaces.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,21 @@ let tom: Person = {
154154

155155
另外,在报错信息中可以看出,此时 `{ name: 'Tom', age: 25, gender: 'male' }` 的类型被推断成了 `{ [x: string]: string | number; name: string; age: number; gender: string; }`,这是联合类型和接口的结合。
156156

157+
一个接口中只能定义一个任意属性。如果接口中有多个类型的属性,则可以在任意属性中使用联合类型:
158+
```ts
159+
interface Person {
160+
name: string;
161+
age?: number;
162+
[propName: string]: string | number;
163+
}
164+
165+
let tom: Person = {
166+
name: 'Tom',
167+
age: 25,
168+
gender: 'male'
169+
};
170+
```
171+
157172
## 只读属性
158173

159174
有时候我们希望对象中的一些字段只能在创建的时候被赋值,那么可以用 `readonly` 定义只读属性:

0 commit comments

Comments
 (0)