You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Type checker doesn't understand string literal type in computed property key #15534
index.ts(9,7): error TS2345: Argument of type '{ [x: string]: number; }' is not assignable to parameter of type 'Thing'.
Property 'foo' is missing in type '{ [x: string]: number; }'.
Right now the commented line in onChange does not typecheck. The compiler doesn't realize that a { [k: keyof LoginState]: string } can be assigned to a Pick<LoginState, K extends keyof LoginState>.
We currently bypass this by calling this.setState({ ...this.state, [property]: event.target.value }), but this essentially bypasses the typechecker (e.g. calling this.setState({ ...this.state, foo: 'bar' }) compiles as well). It's also passing more keys than necessary to setState, and making it do unnecessary work.
type theProp = 'someprop';
const propName: theProp = 'someprop';
interface Some {
someprop?: number;
}
// Correctly gives error
const literalProp: Some {
someprop: true,
}
// Could know that the only possible value of `prop` is `someprop` and give error
const dynamicProp: Some = {
[propName]: true,
}
Activity
mhegazy commentedon May 3, 2017
Duplicate of #5579
whatisaphone commentedon May 4, 2017
Here's a more real-world example where this would be helpful, in the context of React:
Relevant definition of
setState:Right now the commented line in
onChangedoes not typecheck. The compiler doesn't realize that a{ [k: keyof LoginState]: string }can be assigned to aPick<LoginState, K extends keyof LoginState>.We currently bypass this by calling
this.setState({ ...this.state, [property]: event.target.value }), but this essentially bypasses the typechecker (e.g. callingthis.setState({ ...this.state, foo: 'bar' })compiles as well). It's also passing more keys than necessary tosetState, and making it do unnecessary work.jacobrask commentedon May 8, 2017
I have a similar issue.
Code-Stars commentedon Sep 22, 2017
This bug should be fixed. I am also having this issue. See this post on Stackoverflow: https://stackoverflow.com/questions/46361905/property-is-missing-in-type-x-string-string
mhegazy commentedon Sep 22, 2017
This should be fixed in by #18317, give
typescript@nexta try.