Typescript 极简版笔记--接口

120 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第13天,点击查看活动详情

接口

config: SquareConfig:表示传入的config参数使用SquareConfig限制,config可以传color和width参数,但不能传多其它参数,表示可选表示可以少传,没有用表示的则是必传

{ color: string; area: number } 表示返回的类型需要是这个格式

createSquare({color: "black"})只传入了color,ts会提示缺少len,但不会提示缺少width,因为width是可传,len是必传

if (config.clor) 中由于使用了接口SquareConfig中不存在的属性,所以ts也会提示错误

readonly表示属性只能读,不能进行操作

interface SquareConfig {
  color?: string;//可选属性
  width?: number;
  len:number;
  readOnly big:string
}
function createSquare(config: SquareConfig): { color: string; area: number } {
  let newSquare = {color: "white", area: 100};
  if (config.clor) {
    newSquare.color = config.clor;//属性“clor”在类型“SquareConfig”上不存在
  }
  if (config.width) {
    newSquare.area = config.width * config.width;
  }
  config.big = 2 //无法分配到 "big" ,因为它是只读属性。
  return newSquare;
}

let mySquare = createSquare({color: "black"});
//类型 "{ color: string; }" 中缺少属性 "len",但类型 "SquareConfig" 中需要该属性

接口的额外属性

通常用于对某些可能存在其他属性的接口做一些额外的属性

interface SquareConfig { 
  color?: string; 
  width?: number; 
  [propName: string]: any; 
}
let ss:SquareConfig ={
   no:'22' //额外类型 不会报错
}

函数接口

SearchFunc11是定义的一个函数接口,通过里面的写法2,表示接受俩个参数,返回一个布尔值,所以当mySearch在声明的时候用到了SearchFunch11

interface Par{
  source:string;
  subStirng:string
}
interface SearchFunc11 {
     //(par:Par):boolean 
   (source:string,subStirng:string):boolean //写法2
}
let mySearch: SearchFunc11;
mySearch = function(source: string, subString: string) {
  let result = source.search(subString);
  return result > -1;//布尔值
}

可索引类型

通过可索引类型声明一个数组,下标用number

interface StringArray {
  [index: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];
console.log(myStr)
console.log(myArray[0])

通过可索引类型声明一个对象,下标用string

interface StringObj {
    [index:string]:string,
    //readOnly [index:string]:string, //可以声明为只读
}
let myObj:StringObj = {
    name:'111',
    age:'222'
}
console.log(myObj.name,myObj['age'])

类接口

声明一个类同样也可以使用接口,接口描述了类的公共部分,而不是公共和私有两部分。 它不会帮你检查类是否具有某些私有成员

interface ClockInterface {
  currentTime: Date;
  setTime(d: Date):void;
}

class Clock implements ClockInterface {
  currentTime: Date;
  setTime(d: Date) {
      this.currentTime = d;
  }
  constructor(h: number, m: number) { 
    this.currentTime = new Date()
  }
}

接口继承

接口可以使用extends进行继承 直接看代码

interface Shape {
  color: string;
}

interface PenStroke {
  penWidth: number;
}

interface Square extends Shape, PenStroke {
  sideLength: number;
}

let square = <Square>{};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;

混合类型接口

在一个对象中混合了函数和属性

interface Counter {
  (start: number): string;
  interval: number;
  reset(): void;
}

function getCounter(): Counter {
  let counter = <Counter>function (start: number) { };
  counter.interval = 123;
  counter.reset = function () { };
  return counter;
}

let cc = getCounter();
cc(10);
cc.reset();
cc.interval = 5.0;