首页 > 解决方案 > 通用类型 K 是 M 的键,而 M[key] 是特定类型

问题描述

有没有办法定义一种类型:

K extends keyof Interface1 and interface1[K] is type of Interface2

谢谢

标签: typescripttypescript-generics

解决方案


如果我理解正确,您想从中选择Interface1一个值为Interface2.

可以这样实现:

type PropertyOfValue<T, V> = {
  [K in keyof T]-?: T[K] extends V
    ? K
    : never
}[keyof T];

type MyType = PropertyOfValue<Interface1, Interface2>;

用法:

interface Interface1 {
  foo: string;
  bar: Interface2;
}

interface Interface2 {
  baz: string;
}

type MyType = PropertyOfValue<Interface1, Interface2>; // "bar"

操场


推荐阅读