Bug: Type safety violation by undefined default value for component state.
See original GitHub issueUnless a value is explicitly assigned in the constructor, the property state
in React.Component<P, S, SS>
has the default value undefined
, regardless of the specific type passed to the relevant type parameter S
. This leads to a violation of type safety, as shown by the following code example. Furthermore, the value undefined
is not actually assignable to the empty object literal type {}
, the default value for the type parameter S
.
React version: 17.0.1
Minimal code example:
import React from 'react';
class MyComponent extends React.Component<{}, {value: string}> {
constructor(props: {}) {
super(props);
console.log(this.state.value);
}
}
new MyComponent({}); // Compiles OK, TypeError at runtime.
The current behavior
The minimal code example compiles without error but raises TypeError
at runtime, with error message "Cannot read property 'value' of undefined"
.
The expected behavior
The minimal code example should (ideally) raise error at compile time.
Additional information
For the sake of completeness, the example was run using react-scripts
and the following tsconfig.json
(but the issue is not related to react-scripts
):
{
"compilerOptions": {
"target": "esnext",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"noImplicitReturns": true,
"noImplicitThis": true,
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}
Issue Analytics
- State:
- Created 3 years ago
- Comments:8
Yup! I think I initially misunderstood what you were suggesting, but given the clarification above– this sounds like something that should be discussed in DefinitelyTyped 😄 Good luck!
It seems like this issue is requesting new functionality from the TypeScript compiler. The React repro does not have any relationship to the TypeScript compiler. You might want to try filing an issue in that repo: https://github.com/microsoft/TypeScript