对象重新映射的高级输入

时间:2020-03-19 03:22:51

标签: typescript

我正在尝试创建一个函数,该函数允许调用者在给定特定映射的情况下重新映射对象。结果对象应该能够知道新的新字段名称和类型。

这可能是打字稿吗?我认为目前我需要的只是一个返回类型。这是我无法使用的代码:

const mapping = {
    a: "learn",
    b: "state"
}

const original = {
    a: false,
    b: 0
}

const map = <
    Mapping,
    Original
>(
    mapping: Mapping,
    states: Original
): {
    [key: Mapping[key]]: Original[key] //WHAT IS THE CORRECT TYPE HERE?
} => {
    return Object.keys(original).reduce((total, key) => {
        return {
            ...total,
            [mapping[key]]: original[key] //THERE IS AN ERROR HERE TOO BUT I AM NOT WORRIED ABOUT THAT RIGHT NOW
        }
    }, {})
}

const remapped = map(mapping, original)

console.log(remapped)
console.log(remapped.learn)
console.log(remapped.state)

我实质上是想将a重命名为learn,并将b重命名为state。该代码在功能上正常工作,但出现类型错误(“键”是指一个值,但在此处被用作类型。)。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

首先,您需要在工具箱中使用@jcalz令人惊叹的UnionToIntersection实用程序类型。

type UnionToIntersection<U> = 
  (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never;

现在让我们创建自己的实用程序类型:

1    type Remap<A extends { [k: string]: string }, B> =
2        keyof B extends keyof A ?
3        { [P in keyof B & keyof A]: { [k in A[P]]: B[P] } } extends
4        { [s: string]: infer V } ? 
5        UnionToIntersection<V>
6        : never
7        : never;

说明:

  • ln:1,将A的值约束为字符串。
  • ln:2,约束所有B的键都存在于A
  • ln:3,映射到{ "a": {"learn": boolean}, "b": {"state": number} }
  • ln:4,取值部分,其变为:{"learn": boolean} | {"state": number}联合
  • ln:5,应用UnionToIntersection魔法!

放在一起:

const mapping = {
    a: "learn",
    b: "state",
} as const;   // mark as `const` is necessary to infer value as string literal
              // else it'll just be string
const original = {
    a: false,
    b: 0,
};

const map = <
    M extends { [k: string]: string },
    O extends { [k: string]: any }
>(mapping: M, original: O): Remap<M, O> => {
    return Object.keys(original).reduce((total, key) => {
        return {
            ...total,
            [mapping[key]]: original[key]
        }
    }, {} as any); // as any to mute error
};

Playground


我遇到了jcalz的另一个answer,它比我的解决方案更优雅。检查该答案以获取解释。我将其附加在这里:

type Remap2<
    M extends { [k: string]: string },
    O extends { [P in keyof M]: any }
> = {
    [P in M[keyof M]]: O[
        { [K in keyof M]: M[K] extends P ? K : never }[keyof M]
    ]
};