typescript接口

2020-04-30  本文已影响0人  逸崖

接口主要用来规范一些行为实现某些契约,比如是否支持什么属性,类型或者方法。
1 属性接口

interface LabelledValue {
  label: string;
}
function printLabel(labelledObj: LabelledValue) {
  console.log(labelledObj.label);
}
let myObj = { a: 10, label: 'Size 10 Object' };
printLabel(myObj);

let newObj: LabelledValue = {label: '22'}

--- 函数参数只要有其中一种属性就是符合接口,对象需要一致。

2 函数类型接口

interface printInterface{
    (firstName:string,secondName:string):string;
}
const printName: printInterface = function(firstName:string,secondName:string):string {
    return firstName + secondName
}

3 可索引接口 主要是约束数组或者对象

interface arr {
  [index: number]: string;
}
interface obj {
  [index: string]: string;
}

4 类类型接口

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

5 接口扩展

interface Shape {
    color: string;
}
interface Square extends Shape {
    sideLength: number;
}
let square = <Square>{};
square.color = "blue";
square.sideLength = 10;

// 继承多个
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;

6 混合类型

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 c = getCounter();
c(10);
c.reset();
c.interval = 5.0;

7 接口继承类

class Control {
     state: any;
}
interface SelectableControl extends Control {
    select(): void;
}
// 错误:“Image”类型缺少“state”属性。
class Image implements SelectableControl {
    select() { }
}

8 其他 可选属性 & 只读属性

interface FullName {
  firstName: string;
  secondName?: string;
  readonly otherName: string;
}
上一篇下一篇

猜你喜欢

热点阅读