如何 return 从 TS 中的数组中提取相应(按索引)窄类型的记录
How to return a Record of corresponding (by index) narrow types extracted from an array in TS
我的处境可以用以下示例来概括:
interface Config {
readonly key: string,
readonly config: number,
}
// narrow typed array
const arr = [{key:"hi", config:34}, {key:"hello", config:75}] as const;
function fn<T extends ReadonlyArray<Config>>(configs: T) {
type ks = T[number]['key'];
type cs = T[number]['config'];
return {} as {
[K in ks]: cs
}
}
const res = fn(arr);
我需要 {hi:34, hello:75}
作为 return 类型,但目前 res
的类型是 {hi:34|75, hello:34|75}
。我不知道我应该在 cs
上执行哪些其他类型的操作来获得我需要的东西,也不知道使用 cs
是否是正确的方法。
您可以用户提取以获取与当前键对应的元组项的联合中的项:
interface Config {
readonly key: string,
readonly config: number,
}
// narrow typed array
const arr = [{key:"hi", config:34}, {key:"hello", config:75}] as const;
function fn<T extends ReadonlyArray<Config>>(configs: T) {
type ks = T[number]['key'];
type cs = T[number];
return {} as {
[K in ks]: Extract<cs, {key: K}>['config']
}
}
const res = fn(arr); // { hi: 34; hello: 75; }
我的处境可以用以下示例来概括:
interface Config {
readonly key: string,
readonly config: number,
}
// narrow typed array
const arr = [{key:"hi", config:34}, {key:"hello", config:75}] as const;
function fn<T extends ReadonlyArray<Config>>(configs: T) {
type ks = T[number]['key'];
type cs = T[number]['config'];
return {} as {
[K in ks]: cs
}
}
const res = fn(arr);
我需要 {hi:34, hello:75}
作为 return 类型,但目前 res
的类型是 {hi:34|75, hello:34|75}
。我不知道我应该在 cs
上执行哪些其他类型的操作来获得我需要的东西,也不知道使用 cs
是否是正确的方法。
您可以用户提取以获取与当前键对应的元组项的联合中的项:
interface Config {
readonly key: string,
readonly config: number,
}
// narrow typed array
const arr = [{key:"hi", config:34}, {key:"hello", config:75}] as const;
function fn<T extends ReadonlyArray<Config>>(configs: T) {
type ks = T[number]['key'];
type cs = T[number];
return {} as {
[K in ks]: Extract<cs, {key: K}>['config']
}
}
const res = fn(arr); // { hi: 34; hello: 75; }