Ts的接口

1.对json进行限制

interface JsonFomat {
  name: string; // 必须存在name
  readonly age: number; // 必须存在age
  [propName: string]: any; //其他属性,可有可无
}

let json1: JsonFomat = {
  name: "张三",
  age: 18,
};
let json2: JsonFomat = {
  name: "张三",
  age: 18,
  defineName: "自定义",
};
// json2.age= 20;  // 只读属性不能赋值

2.对函数进行限制

interface Fn {
  (name: string, age: number): void;
}
let fn1: Fn = (name: string) => {
  return name + "_define";
};
let fn2: Fn = (name: string, age: number) => {
  console.log(name + "_define" + age);
};

3.类 实现接口,要实现接口里面的属性和方法

interface Animal {
  name: string;
  eat(): void;
}
interface People {
  name: string;
  age: number;
}

enum WSex {
  man = "男",
  woman = "女",
}

interface Womans extends People {
  sex: WSex;
}

// 接口继承
class Cat implements Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  eat(): void {
    console.log("猫吃鱼");
  }
}
// 实现多个接口
class Mans implements Animal, People {
  name: string; // Animal
  age: number; // People
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
  // Animal
  eat(): void {
    console.log("狗吃骨头");
  }
}

// 接口继承别的接口,那父和子的属性和方法都要实现
class Nv implements Womans {
  sex: WSex = WSex.man; // Womans
  name: string; // People
  age: number; // People
  constructor(name: string, age: number, sex: WSex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
  }
}

3.可索引接口

interface Arr {
  [index: number]: string;
}
let ar: Arr = ["1", "2", "3"];

4.构造函数类型 接口

class Ani {
  constructor(public name: string, public age: number) {
    this.name = name;
    this, (age = age);
  }
}
class Ani2 {
  age: number;
  constructor(public name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}
class Ani3 {
    constructor(public name: string) {
      this.name = name;
    }
  }
interface Cons {
  new (name: string, age: number): Ani;
}

function createClass(cla: Cons, name: string, age: number) {
  return new cla(name, age);
}
let cc = createClass(Ani, "张三", 18);
let cc2 = createClass(Ani2, "张三", 18);
// let cc3 = createClass(Ani3, "张三", 18);  // 报错,构造函数要一样

 

你可能感兴趣的:(Typescript,typescript)