Indexed Accesses Checking Allow Unsafe Assignments #26274
Closed
Description
Code
class Component<S> {
state!: S; // assume a default state is provided in some way
setState<K extends keyof S>(state: Pick<S, K>) { /*react-like setState*/ }
}
export interface State<T> {
a: T;
}
class Foo {}
class Comp<T extends Foo, S> extends Component<S & State<T>>
{
foo(a: T) {
this.setState({ a: a });
}
}
Expected behavior:
Error on setState
- a T
is not inherently comparable with a S["a"]
- since S
is unconstrained, so too is S["a"]
.
For a concrete subtype which exposes the issue, consider:
class BrokenComponent extends Comp<Foo, { a: { x: number } }> {
main() {
const f = new Foo();
this.foo(f); // allowed
this.state.a.x; // According to the typesystem, this should exist, but it won't!
}
}
Actual behavior:
No error.