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

React useState hook gets typed incorrectly

$
0
0

When I try to use useState hook without default value it get's typed incorrectly. It doesn't include undefined in possible types. For example in component bellow:

type Color = 'blue' | 'yellow' | 'red';const MyComponent: React.FC = () => {  const [color, setColor] = useState<Color>();  color.toLocaleLowerCase();  return null;};

The color is typed as Color and therefore color.toLocaleLowerCase() won't raise any typescript error, even though in reality the color can also be undefined (which of course, would cause runtime error).

I even tried specifying the undefined explicitly as possible type: const [color, setColor] = useState<Color | undefined>(); but color is still typed just as Color.

I am almost sure that this used to work. Did anyone else ran into similar issue?

Some dependencies:

"react": "16.9.0","expo": "^37.0.0","react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz","@babel/preset-typescript": "^7.8.3","@typescript-eslint/parser": "^2.28.0","@typescript-eslint/eslint-plugin": "^2.28.0","typescript": "^3.8.3",

My tsconfig.json:

{"compilerOptions": {"allowJs": true,"allowSyntheticDefaultImports": true,"jsx": "react-native","lib": ["dom", "esnext"],"moduleResolution": "node","noEmit": true,"skipLibCheck": true,"noImplicitAny": true,"resolveJsonModule": true,"esModuleInterop": true,"isolatedModules": false,"baseUrl": "./","sourceMap": true,  }}

Viewing all articles
Browse latest Browse all 6213

Trending Articles



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