ts-接口(1)

本篇LIst

什么是接口?
定义一个接口
可选属性接口
只读属性接口
可添加属性接口
函数接口

什么是接口

ts-接口(1)_第1张图片

定义接口

// 1.定义一个接口

interface Person {
    pName: string;
    pAge: number;
    pSex: string;
  }
  
  let person: Person = {
    pName: "xiaoming",
    pAge: 18,
    pSex: "woman",
  };
  
  function printPerson(person: Person): void {
    console.log(`kkkkk${person.pName}`);
  }
  

可选属性接口

// 2.接口-可选属性

interface Circle {
  color: string;
  area: number;
}

interface CircleConfig {
  color?: string;
  radius?: number;
}

function createCircle(config: CircleConfig): Circle {
  let newCirlce: Circle = { color: "blue", area: 10 };
  if (config.color) {
    newCirlce.color = config.color;
  }
  if (config.radius) {
    newCirlce.area = config.radius;
    newCirlce.area = config.radius * config.radius * Math.PI;
  }
  return newCirlce;
}

let circle1: Circle = createCircle({ color: "red" });
let circle2: Circle = createCircle({ radius: 20 });

只读属性接口

// 3.只读属性-初始化之后不能修改

interface FullName {
  readonly firstName: string;
  readonly lastName: string;
}
let perName: FullName = { firstName: "liu", lastName: "dongyang" };

//4. ReadonlyArray 只读数组. 禁用修改数组的方法,不予许进行修改
//不可以把只读数组赋给普通数组,如果要赋值利用断言进行转化
let re: ReadonlyArray = [1, 2, 3, 4, 5];

可添加属性接口

//5.要传入额外的属性
// 利用断言来跳过ts的类型检查
let myCircle = createCircle({ color: "adad", black: "true" } as CircleConfig);

//字符串索引签名
interface Ecircle {
  color: string;
  radius: number;
  //字符串索引签名
  [propsName: string]: any;
}

//利用属性检查的是最外层的
let circleOption = { color: "red", radius: 12, ridusssss: 21 };
let mtCircle = createCircle(circleOption);

函数接口

//6. 函数类型
interface CompareFuc {
  (first: number, last: number): boolean;
}

let myCompare: CompareFuc = function (first: number, last: number): boolean {
  return first > last;
};

let myCompare2: CompareFuc = function (a: number, b: number): boolean {
  return a > b;
};
let myCompare3: CompareFuc = function (a, b) {
  return a > b;
};

你可能感兴趣的:(ts-接口(1))