说明

上一小节通过接口约束了类,本小节来说一下通过接口约束TypeScript中的对象。

使用

使用接口约束ts中的对象,可以强制对象按照要求进行定义:

  1. // 定义一个接口
  2. interface UserInterface {
  3. username: string,
  4. age: number,
  5. sex?: string | number,
  6. fn: ()=>void
  7. }
  8. // 定义一个对象,通过接口来进行约束
  9. const User: UserInterface = {
  10. username: 'root',
  11. age: 30,
  12. sex: '男',
  13. fn() {console.log(123)}
  14. }

上面的代码中,定义的接口UserInterface 中包含了三个属性一个方法,其中sex属性为可选属性,也就是说,除了sex属性,其他的两个属性和fn方法,凡是使用该接口进行约束的,都需要实现。

注意

如果需要放置额外的属性,可以如下:
image.png

总结

使用接口约束对象,可以让对象按照约定来编写,无论是属性还是方法。当然,也可以将属性和方法设置为可选的,并且也可以允许对象添加额外的属性,只要符合类型约束即可。