typescript - 当 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;
}
我只是创建了一个无法使用的界面吗?如何使用这样的接口?
请不要介意这个例子没有任何意义。我问这个问题是为了学习语言。
解决方案
我不确定是否有允许您直接定义它的语法,但我能够让它以这种方式编译:
interface MyInterface {
attr1: number;
(): number;
}
const x = () => 1
x.attr1 = 10
const y: MyInterface = x
由于函数实际上只是 JavaScript 中的某种类型的对象,因此这是完全合法的。如果你调用它(y()
)它是可调用的,但它也可以有额外的属性(y.attr1
)
推荐阅读
- node.js - 我目前正在安装“npm install --save dev webpack webpack-dev-server”,但我遇到了这个问题
- php - 致命错误:在 Laravel 7.0 的第 29 行的 Foundation\Application.php 中找不到接口“Symfony\Component\HttpKernel\HttpKernelInterface”
- typescript - 在打字稿中,计算后无法引用类型
- linux - 查看重定向到 dev/null 的进程输出 - 撤消重定向
- python - Pyplot 在绘制 1d 列与 nd 列时绘制不同的线型和标记样式
- mysql - 带有自我声明序列列的 MYSQL QUERY
- typescript - Typescript 条件类型无法正确缩小嵌套属性的类型
- java - Mockito 正确地模拟了服务,但它不适用于删除模拟
- ubuntu - 如何根据“Base”中的新安装更新 conda 的虚拟环境?
- python - Pandas DataFrame 中的列表到字符串转换