Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - How to add a method outside the class definition

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')
}
like image 474
sam sha Avatar asked Jul 18 '16 09:07

sam sha


People also ask

Can methods be defined outside of a class?

Yes you can definitely have functions outside of a class.

Can we define a method outside the class how and why?

No its not possible. In java everything (objects) belongs to some class. So we can not declare function(method) outside a class.

Can you define attributes and methods outside a class in Java?

Edit You can have public methods in non-public classes, but you probably don't want that since the non-public classes will have limited (perhaps none) visibility outside of the declaring class.


1 Answers

It complains 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')
}
like image 157
Nitzan Tomer Avatar answered Sep 26 '22 13:09

Nitzan Tomer