02-TS的interface

172 阅读2分钟

01 接口

// ! 接口
// ! 是对象的状态(属性)和行为(方法)的抽象(描述)
// ! 是一种类型,是一种规范或者一种规则或者一种约束或者一种能力
/**
 * ! 接口类型的对象
 *   ! 可选属性: ?
 *   ! 只读属性: readonly
 */
(() => {
  // *需求: 创建人的对象, 需要对人的属性进行一定的约束;
  // *id是number类型, 必须有, 只读的;
  // *name是string类型, 必须有;
  // *age是number类型, 必须有;
  // *sex是string类型, 可以没有;
  // todo 定义一个接口,该接口作为person对象类型的使用,限定或约束该对象属性数据
  interface IPerson {
    //* readonly id 是只读的
    readonly id: number;
    name: string;
    age: number;
    //* ? 可选属性
    sex?: string;
  }
  // todo 定义一个对象,该对象的类型就是我定义的接口
  const person: IPerson = {
    id: 11,
    name: "45",
    age: 15,
    // sex: "不知道",
  };
  console.log("person: ", person);
})();

02 函数的类型

//! 函数的类型
//! 通过接口的方式作为函数的类型来使用
//! 它就像是一个只有参数列表和返回值类型的函数定义。参数列表里的每个参数都需要名字和类型。
(() => {
  // 定义一个函数的类型,作为某个函数的类型来使用
  interface ISearchFun {
    // *定义一个调用签名
    (source: string, sub: string): boolean;
  }
  // *定义一个函数,类型就是上面的接口
  const searchString:ISearchFun = function (source: string, sub: string): boolean {
    // 在source中寻找sub的
    return source.search(sub) > -1;
  };
  //* 调用函数
  console.log(searchString("哈哈唉", "唉"));
})();

03 类 类型

//! 类 类型:类的类型可以通过接口来实现
(() => {
  //? 定义一个接口
  interface IFly {
    //* 该方法没有任何的实现(什么都没有)
    fly(): any;
  }
  //? 定义一个类。这个类的类型上上面定义的接口(实际上,IFly约束了当前的这个Person的类)
  class Person implements IFly {
    //? 实现接口中的方法
    fly() {
      console.log("看看我");
    }
  }
  //? 实例化对象
  const person = new Person();
  person.fly();

  interface ISwim {
    swim(): any;
  }
  //todo 定义一个类,这个类的类型就是IFly和ISwim(当前这个类可以实现多个接口,一个类可以被多个接口进行约束)

  class Person2 implements IFly, ISwim {
    fly() {
      console.log("看看我,我是第二个");
    }
    swim() {
      console.log("看看我 我是第二个");
    }
  }
  const person2 = new Person2();
  person2.fly();
  person2.swim();

  //! 类可以通过接口的方式,来定义当前这个类的类型
  //! 类可以实现一个接口,类也可以实现多个接口,要注意,接口中的内容都要真正的实现
  //! 接口可以继承其他人的多个接口

  //定义了一个接口,并且继承了上面的接口
  interface IWan extends Person2, Person {}

  //定义一个类,直接实现IFly和ISwim
  class Person3 implements IWan {
    fly() {
      console.log("看看我,我是3个");
    }
    swim() {
      console.log("看看我 我是第3个");
    }
  }
  const person3 = new Person3();
  person3.fly();
  person3.swim();

  //! 接口和接口之间叫继承(使用的是extends)
  //! 类和接口之间叫实现(使用的是implements)
})();