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.
CodePudding user response:
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
}
}
CodePudding user response:
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
}
}

