admin管理员组

文章数量:1400167

typescript, how to add a method outside the class definition

I try to add it on prototype, but error

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')
}

typescript, how to add a method outside the class definition

I try to add it on prototype, but error

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')
}
Share Improve this question asked Jul 18, 2016 at 9:08 sam shasam sha 8529 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

It plains because you did not define that B has the method say.
You can:

class B {
    name: string = 'sam.sha'
    say: () => void;
}

B.prototype.say = function(){
    console.log('define method in prototype')
}

Or:

class B {
    name: string = 'sam.sha'
}

interface B {
    say(): void;
}

B.prototype.say = function(){
    console.log('define method in prototype')
}

本文标签: javascriptTypeScriptHow to add a method outside the class definitionStack Overflow