Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct type of a 'set' function in TypeScript?

Tags:

typescript

I have a function in TypeScript like this:

set parameter(value: string) {
  this._paremeter = value;
}

This works fine. I thought for the sake of completeness: Let's add the correct type that says this function doesn't retun anything. However, none is working:

set parameter(vale: string): void {}
set parameter(vale: string): never {}

I also tried these, just to make sure. But of course any of these won't work either:

set parameter(vale: string): undefined {}
set parameter(vale: string): null {}

Is there a correct type or should a set-function simply have no type at all?

like image 633
lampshade Avatar asked Oct 15 '25 14:10

lampshade


2 Answers

Setters do not support specifying a return type.

From the (now deprecated) language specification:

SetAccessor:
set PropertyName ( BindingIdentifierOrPattern TypeAnnotation (optional) ) { FunctionBody }

like image 50
Jack Wilsdon Avatar answered Oct 18 '25 07:10

Jack Wilsdon


From the Typescript documentation

TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives you a way of having finer-grained control over how a member is accessed on each object.

And there is an example of a set

set fullName(newName: string) {
        if (newName && newName.length > fullNameMaxLength) {
            throw new Error("fullName has a max length of " + fullNameMaxLength);
        }

        this._fullName = newName;
    }

In concluision, a set method cannot return a type so, your first approach is the right one.

set parameter(value: string) {
  this._paremeter = value;
}
like image 20
Diego Bascans Avatar answered Oct 18 '25 07:10

Diego Bascans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!