TypeScript-函数接口和混合类型接口

函数接口

  • 我们除了可以通过接口来限定对象以外, 我们还可以使用接口来限定函数
interface SumInterface {
    (a: number, b: number): number
}

let sum: SumInterface = function (x: number, y: number): number {
    return x + y;
}
let res = sum(10, 20);
console.log(res);

混合类型接口

  • 约定的内容中, 既有对象属性, 又有函数
  • 如果这个时候我有一个需求,就是要求定义一个函数实现变量累加

  • 分别来看看,没有使用 混合类型接口 之前不同的实现方案

  • 方式一(会污染全局空间)

let count = 0;

function demo() {
    count++;
    console.log(count);
}

demo();
demo();
demo();
  • 方式二(使用闭包)
  • 使用闭包确实可以解决污染全局空间的问题, 但是对于初学者来说不太友好
let demo = (() => {
    let count = 0;
    return () => {
        count++;
        console.log(count);
    }
})();

demo();
demo();
demo();
  • 方式三(利用 JS 中函数的本质)
  • 在 JS 中函数的本质就是一个对象,然后我们就可以直接给该对象添加一个 count 属性进行累加
  • 第三种方式在 TS 当中进行编写是会报错的,要想在 TS 当中进行使用就需要使用到 混合类型接口,如果想要验证第三种方式可以新建一个 JS 文件在其中进行编写和运行即可
let demo = function () {
    demo.count++;
}
demo.count = 0;
demo();
demo();
demo();

使用混合类型接口

interface CountInterface {
    (): void

    count: number
}

let getCounter = (function (): CountInterface {
    let fn = <CountInterface>function () {
        fn.count++;
        console.log(fn.count);
    }
    fn.count = 0;
    return fn;
})();
getCounter();
getCounter();
getCounter();
  • 如上代码 CountInterface 接口要求数据既要是一个没有参数没有返回值的函数, 又要是一个拥有 count 属性的对象
  • fn 作为函数的时候符合接口中函数接口的限定 ():void
  • fn 作为对象的时候符合接口中对象属性的限定 count:number

image-20211128031117336

end02

posted @ 2021-11-28 03:12  BNTang  阅读(725)  评论(0编辑  收藏  举报