如何获取数组所有可能的索引作为数字联合类型?
数字联合类型的预期结果:
type VoiceSettings = {
similarityLevel: 0 | 1 | 2 | 3 | 4 | 5;
stabilityLevel: 0 | 1 | 2 | 3 | 4;
}
实际结果:
type VoiceSettings = {
similarityLevel: "0" | "1" | "2" | "3" | "4";
stabilityLevel: "0" | "1" | "2" | "3" | "4";
}
代码:
const VALUES_MAP = {
similarityLevel: [0, 15, 30, 50, 75, 90],
stabilityLevel: [15, 30, 60, 75, 90],
} as const;
type ValuesTypes = keyof typeof VALUES_MAP;
type VoiceSettings = {
[key in ValuesTypes]: Exclude<keyof (typeof VALUES_MAP)[ValuesTypes], keyof []>;
};
这里是TS游乐场
来自这个答案关于我提出的重复问题:
您可以使用以下类型:
type Indices<T extends readonly any[]> = Exclude<Partial<T>["length"], T["length"]>
对于你的问题,看起来像这样:
const VALUES_MAP = {
similarityLevel: [0, 15, 30, 50, 75, 90],
stabilityLevel: [15, 30, 60, 75, 90],
} as const;
type ValuesTypes = keyof typeof VALUES_MAP;
type Indices<T extends readonly any[]> = Exclude<Partial<T>["length"], T["length"]>
type VoiceSettings = {
[key in ValuesTypes]: Indices<typeof VALUES_MAP[key]>;
};
其中
VoiceSettings
输入为:
type VoiceSettings = {
similarityLevel: 0 | 5 | 1 | 2 | 3 | 4;
stabilityLevel: 0 | 1 | 2 | 3 | 4;
}
这里是TS游乐场