'How to declare static variables as possible return types in TypeScript
I'm trying to declare a return type from a simple getter in TypeScript. That return type should conform to one of two static variables, associated with the class that implements them.
Take this code:
class Hairdryer {
public static ON = 'ON'
public static OFF = 'OFF'
private _state: Hairdryer.ON|Hairdryer.OFF = Hairdryer.OFF
get state (): Hairdryer.ON|Hairdryer.OFF {
return this._state
}
}
The TypeScript compiler doesn't like this, and throws errors:
'Hairdryer' only refers to a type, but is being used as a namespace here.(2702)
Return type of public getter 'state' from exported class has or is using private name 'Hairdryer'.(4043)
I know I could just have 'ON'|'OFF' as my return type, but I wanted to be able to reference the possible types from outside the class, without instantiating it, hence the use of static properties.
Here's a playground link.
Solution 1:[1]
Ill suggest you to use Enum instead of static values inside the class this is more TS friendly.
enum State {
ON = 'ON',
OFF = 'OFF'
}
class Hairdryer {
public static state = State;
private _state: State= State.OFF
get state (): State {
return this._state
}
}
Solution 2:[2]
You need to use an index access type on the static part of the class (typeof Hairdryer not Hairdryer)
type State = typeof Hairdryer['ON']| typeof Hairdryer['OFF'];
class Hairdryer {
public static ON = 'ON' as const
public static OFF = 'OFF' as const
private _state: State= Hairdryer.OFF
get state (): State {
return this._state
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Titian Cernicova-Dragomir |

