小编blu*_*ere的帖子

如何使用打字稿中的查找来推断类型化的mapValues?

如同:

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

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

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

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, …
Run Code Online (Sandbox Code Playgroud)

typescript typescript-typings

6
推荐指数
1
解决办法
2903
查看次数

标签 统计

typescript ×1

typescript-typings ×1