I've been trying to make a generic function which receives and object T and receives a string property name of that object T.
I used https://www.typescriptlang.org/docs/handbook/advanced-types.html as an example (section: Distributive conditional types)
I've come up with a solution that works without generics, but when I change the explicit types to a generic type typescript won't compile.
This is the non-generic version:
export type TypedPropertyNames<T, P> = { [K in keyof T]: T[K] extends P ? K : never }[keyof T];
export type StringPropertyNames<T> = TypedPropertyNames<T, string>;
interface Test {
test: string;
}
function non_generic(form: Test, field: StringPropertyNames<Test>): string {
return form[field];
}
This works.
Now when I change the Test interface into a generic argument it won't compile anymore.
export type TypedPropertyNames<T, P> = { [K in keyof T]: T[K] extends P ? K : never }[keyof T];
export type StringPropertyNames<T> = TypedPropertyNames<T, string>;
function generic<T>(form: T, field: StringPropertyNames<T>): string {
return form[field]; // This won't compile
}
Is this expected behaviour? Or is this a typescript bug? Can anyone point me in the direction of making the generic version work (without any hacks)
Update 1:
Compilation error:
Type 'T[{ [K in keyof T]: T[K] extends string ? K : never; }[keyof T]]' is not assignable to type 'string'.