打字稿:我该如何为原型添加功能类型?
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'.`;
答案 0 :(得分:2)
已更新
对于node.js和deno,您需要与undefined
而不是Window
进行比较
interface Fool {
greet(): any;
}
function Fool(this: any, name: string): Fool {
if (this === undefined) { // check if it was called statically.
return new (Fool as any)(name);
}
this.name = name;
return this;
}
Fool.prototype.greet = function () {
console.log(`Fool greets ${this.name}`);
};
Fool("Joe").greet(); // Fool greets Joe
原始
TS中正确的方法是使用类而不是prototype
。然后,您无需解决此问题。
class Fool {
constructor(public name: string) {}
greet() {
console.log(`Fool greets ${this.name}`);
}
}
new Fool("Joe").greet(); // Fool greets Joe
如果您仍然想使用原型(不推荐使用的原型),则可以进行修复:
interface Fool {
greet(): any;
}
function Fool(this: any, name: string): Fool {
if (this.constructor === Window) { // check if it was called statically.
return new (Fool as any)(name);
}
this.name = name;
return this;
}
Fool.prototype.greet = function () {
console.log(`Fool greets ${this.name}`);
};
Fool("Joe").greet(); // Fool greets Joe
答案 1 :(得分:2)
如果使用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();
答案 2 :(得分:0)
使用此解决方案,您可以同时使用Fool(name)
和new Fool(name)
。
interface Fool {
name: string;
greet(): void;
}
interface FoolConstructor {
new(name: string): Fool;
(name: string): Fool;
}
const Fool = function (this: Fool | void, name: string): Fool {
if (!(this instanceof Fool)) {
return new Fool(name);
}
this.name = name;
return this;
} as FoolConstructor;
Fool.prototype.greet = function(this: Fool) {
console.log(`Fool greets ${this.name}`);
};
console.log(
new Fool('Joe').greet(),
Fool('Joe').greet()
);