Suppose you have a type Type
that takes a record containing tuples with a union of strings and one string from that union (consider it as options and a default), and also takes a union of string builds where each string follows the pattern
${key of first type}:${one of the value in the first type union}
type BuildPart<T extends Record<string, [string, string]>> = '' | {
[K in keyof T]: K extends string ? `${K & string}:${T[K][number]}` : never
}[keyof T]
type Type<All extends Record<string, [string, string]>, Part extends BuildPart<All> = ''> = {
[K in keyof All]: K extends string ? Part extends `${K}:${infer V}` ? V : All[K][1] : never
}[keyof All]
The main objective is to extract values chosen, which can be either the default set originally or any alternative provided by Part
.
type test0 = Type<{a: ['b' | 'c', 'c'], b: ['d' | 'e', 'd']}> // 'c' | 'd'
type test1 = Type<{a: ['b' | 'c', 'c'], b: ['d' | 'e', 'd']}, 'a:b'> // 'b' | 'd'
type test2 = Type<{a: ['b' | 'c', 'c'], b: ['d' | 'e', 'd']}, 'a:b' | 'b:e'> // 'b' | 'c' | 'd' | 'e' but expected 'b' | 'e'
It functions correctly when Part
is empty or contains only one value. However, if Part
is a union, then all possible values are displayed.