javascript - TypeScript - Wie man eine Methode außerhalb der Klassendefinition hinzufügt
TypeScript, wie man eine Methode außerhalb der Klassendefinition hinzufügt
Ich versuche, es zum Prototyp hinzuzufügen, aber Fehler
B.ts
export class B{
name: string = 'sam.sha'
}
//Error:(21, 13) TS2339: Property 'say' does not exist on type 'B'.
B.prototype.say = function(){
console.log('define method in prototype')
}
Antwort #1
Es beschwert sich, weil Sie nicht definiert haben, dass B die Methode say hat.
Sie können:
class B {
name: string = 'sam.sha'
say: () => void;
}
B.prototype.say = function(){
console.log('define method in prototype')
}
Oder :
class B {
name: string = 'sam.sha'
}
interface B {
say(): void;
}
B.prototype.say = function(){
console.log('define method in prototype')
}
