New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unable to assign compatible value to generic typed property using extends
in generic definition.
#15065
Comments
Consider what happens if you write this var t = new GenericComponent<{on: boolean, thing: string}>();
t.onInput({ value: 30 });
t.state.thing.substr(0); // 'thing' property should exist, but doesn't |
Here is a simplified example: class Stateful<State extends { on: boolean }> {
state: State = {
on: true
}; // error
} The reason this doesn't work is that it is only ever going to be valid when Basically, there exists a type So the errant code above asserts that, for all types Logically, we can look at it as follows Assertion
Disproof by counter example
|
@RyanCavanaugh @aluanhaddad Shoot, I knew that. I just got confused while trying to distill the problem down to something simpler. So let try that again. What about in this case using a Partial? I still get a similar error. interface BaseState {
on: boolean;
};
class Component {
state: BaseState;
setState(partialState: Partial<BaseState>) {
this.state = { ...this.state, ...partialState };
}
onInput({ value }: { value: number }) {
this.setState({ on: value > 0 }); // no error
}
}
class GenericComponent<State extends BaseState> {
state: State;
setState(partialState: Partial<State>) {
this.state = { ...this.state, ...partialState };
}
onInput({ value }: { value: number }) {
this.setState({ on: value > 0 }); // error: Argument of type '{ on: boolean; }' is not assignable to parameter of type 'Partial<State>'
}
} |
TypeScript Version: 2.2.2
I might just be misunderstanding how generics work (if so please point me in the right direction), but this seem like a bug.
Code
Expected behavior:
In the
Component
class in the example above causes no errors when using theBaseState
interface directly. I expect the same behavior from theGenericComponent
class since theState
generic explicitly extendsBaseState
.Actual behavior:
Instead I get the following error related to
this.setState({ on: value > 0 });
: "Argument of type '{ on: boolean; }' is not assignable to parameter of type 'State'."The text was updated successfully, but these errors were encountered: