Looking to extract specific types based on a given label
Take a look at the code snippets below:
interface TypeWithLabel {
label: string;
list: string;
}
interface A extends TypeWithLabel{
label: 'a';
list: '1' | '2' | '3';
}
interface B extends TypeWithLabel {
label: 'b';
list: '4' | '5' | '6';
}
type TypeProperty<T, U extends keyof T> = T[U];
function ab<T extends TypeWithLabel, U = TypeProperty<T, 'label'>>(
label: U,
item: TypeProperty<T, 'list'>
) {
}
// retrieve only type A with label:'a'
// and provide options '1' | '2' | '3' for item
ab<A | B>('a', '1'); // correct
ab<A | B>('a', '4'); // error
// obtain only type B with label:'b'
// and display choices '4' | '5' | '6' for item
ab<A | B>('b', '4'); // correct
ab<A | B>('b', '1'); // error
Is there an alternative method to filter these interfaces?
I considered reusing generics, but label
must be provided as a string value in the function.