首页 > 解决方案 > 如何返回从 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}作为返回类型,但目前的类型res{hi:34|75, hello:34|75}. 我不知道我应该执行哪些其他类型的操作cs来获得我需要的东西,也不知道 usingcs是否是正确的方法。

标签: typescripttypescript-generics

解决方案


您可以用户提取以获取与当前键对应的元组项的联合中的项:

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; }

推荐阅读