传递给泛型时合并两个接口的键

Merging keys of two interfaces when passing to generic type

我有两个接口如下:

interface Foo {
  foo: string;
}

interface Bar {
  prop1: string;
  prop2: string;
}

我的目标是创建一个类型,将这两个界面键与它们之间的下划线结合起来,如下所示:

type MergeKeys<A,B> = {
  [P in keyof A + '_' + P2 in keyof B]: string;
};

type Result = MergeKeys<Foo,Bar>;

因此结果将是:

   interface Result {
      foo_prop1: string;
      foo_prop2: string;
    }

这可能吗?

这是一种方法:

type MergeKeys<A, B> = { [P in
  `${Exclude<keyof A, symbol>}_${Exclude<keyof B, symbol>}`
  ]: string; };

主要思想是使用template literal types执行所需的字符串连接。

唯一的问题是编译器会拒绝更简单的 `${keyof A}_${keyof B}`,因为 TypeScript supports symbol-valued keys which cannot be serialized to strings via template literals. In order to convince the compiler to serialize keyof A, we have to get rid of the possibility that any symbol-valued keys will be in there. That's where the Exclude<T, U> utility type comes in. The type Exclude<keyof A, symbol> will return the union of all the keys of A which are not symbols (so you'll get any string or number literal types 但没有 symbols).


好的,我们来测试一下:

type Result = MergeKeys<Foo, Bar>;
/* type Result = {
    foo_prop1: string;
    foo_prop2: string;
} */

看起来不错!

Playground link to code