Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Typescript React | Adding 'as const' on variable has different behavior in playground and IDEs (VSCode, WebStorm)

$
0
0

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.

enter image description here

What I've tried so far

  1. Changing the number types to strings (0 becomes '0', error becomes '-1', success becomes '1')
    • Doesn't work
  2. Removing 'as const', breaks because any number can then be considered as okay
  3. Re-typing state variable with State type works correctly (with as const), but I shouldn't need to because I already added the component?

Edit 3:

  1. 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 of State and yet it thinks that currentState can only have one value? What am I missing?enter image description here

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"

Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>