如何使用打字稿中的查找来推断类型化的 mapValues? [英] How to infer typed mapValues using lookups in typescript?

查看:26
本文介绍了如何使用打字稿中的查找来推断类型化的 mapValues?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于:

如何推断来自打字稿中动态键数组的类型化数组?

我希望键入一个通用对象,该对象接收到查找值的任意键的映射,并返回具有键入值的相同键(如键入的 _.mapValues).

I'm looking to type a generic object which receives a map of arbitrary keys to lookup values, and returns the same keys with typed values (like a typed _.mapValues).

从对象获取单一类型属性的能力已记录并有效.对于数组,您需要将重载硬编码为类型化元组,但对于对象,我收到重复字符串索引签名"错误.

The ability to get a singular typed property from an object is documented and works. With arrays, you need to hardcode overloads to typed tuples, but for objects i'm getting a 'Duplicate string index signature' error.

export interface IPerson {
    age: number;
    name: string;
}

const person: IPerson = {
    age: 1,
    name: ""
}

function getProperty<T, K extends keyof T>(o: T, name: K): T[K] {
    return o[name];
}

const a = getProperty(person, 'age');
// a: number

const n = getProperty(person, 'name');
// n: string

function getProperties<T, K extends keyof T>(obj: T, keys: { [key: string]: K }) {
    const def: { [key: string]: T[K] } = {};
    return Object.entries(keys).reduce((result, [key, value]: [string, K]) => {
        result[key] = getProperty(obj, value);
        return result;
    }, def);
}

const { a2, n2 } = getProperties(person, {
    a2: 'name',
    n2: 'age'
});

// Result:
// {
//     a2: string | number, 
//     n2: string | number
// }

// What I'm looking for:
// {
//     a2: string, 
//     n2: number' 
// }

如何用打字稿实现这一点?

How can this be implemented with typescript?

推荐答案

可能有一种方法可以稍微优化/折叠这种类型,但是我有一个 getProperties 的函数原型我相信可以实现您的目标.

There may be a way to optimize/collapse this typing a little bit, but I've got a function prototype for getProperties that I believe achieves what you are looking for.

您的定义中缺少的是一个强返回类型定义,该定义将 keys 对象中的特定键与 obj 对象中的特定类型之间的关联联系起来.因为缺少了这个,所以一切都变成了类型的联合,这就是你在上面看到的行为.

What's missing in your definition is a strong return type definition that links the association between a specific key in the keys object and the specific type in the obj object. Because this is missing, everything becomes the union of types, which is the behavior you see above.

我想出的函数类型是:

function getProperties
    <T, K extends keyof T, U extends { [name: string]: K }>
        (obj: T, keys: U):
            {[V in keyof U]: T[U[V]];

这里重要的部分是返回值类型:{[V in keyof U]: T[U[V]]}

The important part here is the return value type: {[V in keyof U]: T[U[V]]}

它为keys对象中的每个键V指定:

It specifies that for each key V in the keys object:

  1. V 将是输出对象中的一个键

  1. V will be a key in the output object

值类型将是来自输入 obj 的类型,其中类型来自与 V 中的键关联的值给出的键>U.

The value type will be a type from the input obj, where the type comes from the key given by the value associated with key V in U.

这篇关于如何使用打字稿中的查找来推断类型化的 mapValues?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆