对值所具有的结构进行类型检查。我们使用接口(Interfaces)来定义对象的类型。接口是对象的状态(属性)和行为(方法)的抽象(描述)

普通定义与使用 + 可选&只读属性

  1. //readonly只读属性
  2. //? 可选属性
  3. interface Person {
  4. readonly id: number,
  5. name: string;
  6. sayHello():void;
  7. sex?: string;
  8. }
  9. const personObj: Person = {
  10. id: 1,
  11. name: 'Dan',
  12. sayHello:function(){},
  13. // sex:'男' //可选
  14. }
  15. personObj.id = 2//error

函数类型

接口能够描述 JavaScript 中对象拥有的各种各样的外形。 除了描述带有属性的普通对象外,接口也可以描述函数类型。
为了使用接口表示函数类型,我们需要给接口定义一个调用签名。它就像是一个只有参数列表和返回值类型的函数定义。参数列表里的每个参数都需要名字和类型。

interface SearchFunc {
  //函数要接收两个参数 返回值为boolean
  (source: string, subString: string): boolean
}

const mySearch: SearchFunc = function (source: string, sub: string) {
  //查找参数source中是否有参数sub 
  return source.search(sub) > -1
}
console.log(mySearch('abcd', 'ab')); //true

类类型

与 C# 或 Java 里接口的基本作用一样,TypeScript 也能够用它来明确的强制一个类去符合某种契约。

interface Alarm {
  name: string;
  alert(): any;
}

class Car implements Alarm {
  constructor(public name: string) {}

  alert() {}
}

一个类可以实现多个接口

class Car implements Alarm,Alarm2{}

多个相同接口(合并)

多个相同名字的接口,会进行合并,得到一个新的接口;这个接口的特性一般用在扩展第三方库的接口类型

interface PersonInfo {
    name: string,
    age: number
}

interface PersonInfo {
    name: string,
    height: number
}

let zs: PersonInfo = {
  name: "张三",
  age: 20,
  height: 177,
};

接口继承接口

和类一样,接口也可以相互继承。

interface LightableAlarm extends Alarm, Light {

}

Interface 与 Type 的区别

实际上,在大多数的情况下使用接口类型和类型别名的效果等价,但是在某些特定的场景下这两者还是存在很大区别。

  1. 重复定义的接口类型,它的属性会叠加,这个特性使得我们可以极其方便地对全局变量、第三方库的类型做扩展
  2. 如果我们重复定义类型别名,那么就会报错