node.js - 打字稿中的类型函数原型
问题描述
打字稿:如何为带有原型的函数添加类型?
interface Fool {
greet(): any;
}
function Fool(name: string) {
this.name = name;
}
Fool.prototype.greet = function() {
console.log(`Fool greets ${this.name}`);
};
Fool('Joe').greet();
`Property 'greet' does not exist on type 'void'.`;
解决方案
new
如果用西装构造实例:
interface Fool {
name: string;
greet(): void;
}
interface FoolConstructor {
new (name: string): Fool;
(): void;
}
const Fool = function(this: Fool, name: string) {
this.name = name;
} as FoolConstructor;
Fool.prototype.greet = function() {
console.log(`Fool greets ${this.name}`);
};
new Fool('Joe').greet();
推荐阅读
- javascript - 如何在Angular 2中解析并将一个字段中的值填充到另一个字段中
- c++ - 具有数组引用和移动/复制分配的 C++ reinterpret_cast 安全性
- firemonkey - iOS 通知零星 (FMX)
- google-places-api - Google Places API setFields 和 getDetails
- javascript - 视频播放完毕后如何使用 JavaScript 删除视频?
- c# - 共享相同上下文的多个存储库调用 savechanges 操作
- postgresql-9.6 - PostgreSQL 错误:在远程 dblink 调用中,在不能接受类型记录的上下文中调用的函数返回记录
- python - 如何绘制直方图并在python中并排描述它?
- c# - 为什么此 DataGridView ComboBox 单元格中的 EditedFormattedValue 和实际显示的值没有更新?
- python - 使用 Python 和 SQL 时出现 NamError