我想創建一種型別,它將一個物件的兩個屬性的值組合在一個陣列中。
到目前為止,我的解決方案如下所示:
const CONFIGS = [
{ section: "a", name: "1" },
{ section: "b", name: "2" },
] as const;
type ConfigSections<I extends number> = typeof CONFIGS[I]["section"];
type ConfigSectionEntryName<I extends number> = typeof CONFIGS[I]["name"];
// Allows all permutations of section and name: "a_1" | "a_2" | "b_1" | "b_2" :(
// I only want "a_1" | "b_2"
type CompleteConfigName<I extends number> =
`${ConfigSections<I>}_${ConfigSectionEntryName<I>}`;
但是在型別CompleteConfigName<I extends number>中I似乎允許任何數字,因為型別決議為"a_1" | "a_2" | "b_1" | "b_2". 但我想強制執行特定的索引號I,以便型別結果"a_1" | "b_2"
uj5u.com熱心網友回復:
您應該使用這樣的映射型別:
type CompleteConfigName = {
[K in keyof typeof CONFIGS]: (typeof CONFIGS)[K] extends {
section: infer A, name: infer B
}
? `${A & string}_${B & string}`
: never
}[keyof typeof CONFIGS & `${bigint}`]
CompleteConfigName映射元組中的每個元素以創建字串文字。我們可以用索引這個型別[keyof typeof CONFIGS & '${bigint}']來創建映射型別內所有元素的聯合。
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/484021.html
上一篇:Button'型別中的屬性'fit'不能分配給基本型別'IButton'中的相同屬性。型別“字串”不可分配給型別“適合”
下一篇:識別特定類的陣列元素?[復制]
