Home > other >  How to declare the type of a setter in JavaScript/VSCode/TypeScript?
How to declare the type of a setter in JavaScript/VSCode/TypeScript?

Time:07-28

I have a very simple example, to demonstrate the issue:

class Person {
    _name = '';
    _age  = 0;
    get name() {
        return this._name;
    }
    /**
     * @type {string}
     */
    set name(name) {
        this._name = name;
    }
    get age() {
        return this._age;
    }
    /**
     * @type {number | string}
     */
    set age(age) {
        if (age === 'too old') {
            age = 100000;
        }
        this._age = age;
    }
}

I use VSCode to do typechecking, but why does it fail on the type?

I explicitly say that the age setter can take either a number or a string:

enter image description here

CodePudding user response:

You didn't define the type but instead wrote a JSDoc comment. That doesn't actually affect your code. Thus TypeScript implicitly sets the type number.

If you want the setter to accept both string and number one solution would be to use a union type like this:

set age(age: string | number) {
   ...
}

Keep in mind that you get problems when setting this._age later on because this._age also implicitly has the type number (default value 0) and therefore cannot be assigned a value of type string | number.

CodePudding user response:

I believe you need to wrap your union types in parenthesise to be valid in JSDoc:

/**
* @type {(number | string)}
*/

From the documentation:

Multiple types (type union) This can be a number or a boolean.{(number|boolean)} This means a value can have one of several types, with the entire list of types enclosed in parentheses and separated by |.

  • Related