I know I've added react-native
even though this is really just a reactjs
question.
The code
const ScreenStates = { DEFAULT: 0, ERROR: -1, SUCCESS: 1,} as const;type State = { currentState: typeof ScreenStates[keyof typeof ScreenStates];};type Props = undefined;class TestComponent extends React.Component<Props, State> { state = { currentState: ScreenStates.DEFAULT, }; randomFunc = () => { switch (this.state.currentState) { case ScreenStates.SUCCESS: { break; } default: break; } }; render() { return null; }}
The Issue
In VSCode or WebStorm, it will say that Type '1' is not comparable to type '0'.ts(2678)
but the error goes away if I remove the as const
from ScreenStates
variable.
On the TS Playground or CodePen it doesn't show it as a problem.
What I've tried so far
- Changing the number types to strings (0 becomes '0', error becomes '-1', success becomes '1')
- Doesn't work
- Removing 'as const', breaks because any number can then be considered as okay
- Re-typing
state
variable withState
type works correctly (withas const
), but I shouldn't need to because I already added the component?
Edit 3:
- At first I thought it's because I'm redeclaring it in the class that's why I need to retype it again as
State
, but if I redeclare it with an empty object it tells me that a certain property is missing; which means that it knows that the redeclared state is actually ofState
and yet it thinks thatcurrentState
can only have one value? What am I missing?
Relevant packages in package.json
"@babel/preset-typescript": "^7.12.7","@typescript-eslint/eslint-plugin": "^4.8.2","@typescript-eslint/parser": "^4.8.2","typescript": "^4.1.2"