Thor_Bux Thor_Bux - 20 days ago 9
TypeScript Question

How to write type definition (typescript) for getter/setter

How would I write the type definition file (d.ts) for a javascript code that looks like this

library.js:

Object.defineProperty( SceneNode.prototype, 'name', {
set: function(name)
{
this.setName( name );
},
get: function(){
return this._name;
},
enumerable: true
});


I have so far:

library.d.ts

class SceneNode{
private _name: string;
}


But how would I include the getter/setter into the type definition?

Edit 1:

Added file name for clarification

Answer Source

You would just define the type as though it were a simple attribute. The point of the getter and setter is to make it look as though it is only a simple attribute when in fact some code is running, but it doesn't change the interface from a type view.

So all you need is:

class SceneNode{
    private _name: string;
    public name: string;
}