首页 > 解决方案 > 当 TypeScript 接口同时描述一个对象和一个函数时,它怎么能被使用呢?

问题描述

我正在使用 TypeScript 4.2.4。假设我有以下 TypeScript 代码。

// perfectly legal syntax
interface MyInterface {
    attr1: number;
    (): number;
}

// Compilation error: Type '{ attr1: number; }' provides no match for the signature '(): number'
let x: MyInterface = {
    attr1: 1
};

// Compilation error: Property 'attr1' is missing in type '() => number' but required in type 
let y: MyInterface = () => {
    return 1;
}

我只是创建了一个无法使用的界面吗?如何使用这样的接口?

请不要介意这个例子没有任何意义。我问这个问题是为了学习语言。

标签: typescript

解决方案


我不确定是否有允许您直接定义它的语法,但我能够让它以这种方式编译:

interface MyInterface {
    attr1: number;
    (): number;
}

const x = () => 1
x.attr1 = 10

const y: MyInterface = x

由于函数实际上只是 JavaScript 中的某种类型的对象,因此这是完全合法的。如果你调用它(y())它是可调用的,但它也可以有额外的属性(y.attr1


推荐阅读