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?
Setters do not support specifying a return type.
From the (now deprecated) language specification:
SetAccessor:
set
PropertyName(
BindingIdentifierOrPattern TypeAnnotation (optional))
{
FunctionBody}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With