Below is a simplified example of what I am trying to achieve. The class B has a generic parameter "T" and I want to restrict the allowed values of some method parameters to only those that match the keys of the parameter "T".
In my simplistic understanding, the code below should do what I think I intend. However, I keep encountering errors on the specified lines.
My goal is to limit the values when calling something like the "foo" method to only those that correspond to the T parameter. For instance, b.foo("asdf")
would be acceptable, but b.foo("qwerty")
would not be (as "qwerty" is not in keyof A).
Any guidance on how to make progress with this would be greatly appreciated.
interface A {
asdf: string;
}
type Names<X extends A> = X extends A ? keyof X : never;
class B<T extends A> {
foo(N: Names<T>) {
}
baz(n: Names<T>) {
this.foo("asdf"); // Argument of type '"asdf"' is not assignable to parameter of type 'Names<T>'.ts(2345)
this.foo("qwerty"); // expect an error here, but not the other ones
this.foo(n); // fine?
}
}
interface C extends A {
qwerty: string;
}
class D<T extends C> extends B<T> {
bar() {
this.foo("asdf"); // Argument of type '"asdf"' is not assignable to parameter of type 'Names<T>'.ts(2345)
this.foo("qwerty"); // Argument of type '"qwerty"' is not assignable to parameter of type 'Names<T>'.ts(2345)
this.baz("asdf"); // Argument of type '"asdf"' is not assignable to parameter of type 'Names<T>'.ts(2345)
this.baz("qwerty"); // Argument of type '"qwerty"' is not assignable to parameter of type 'Names<T>'.ts(2345)
}
}