Typescript 泛型类型K是M的键,而M[key]是特定类型

Typescript 泛型类型K是M的键,而M[key]是特定类型,typescript,typescript-generics,Typescript,Typescript Generics,有没有一种方法可以定义一种类型,即: K extends keyof Interface1 and interface1[K] is type of Interface2 谢谢如果我理解正确,您希望从Interface1中选择一个值为Interface2的属性 可以通过以下方式实现: type PropertyOfValue<T, V> = { [K in keyof T]-?: T[K] extends V ? K : never }[keyof T]; t

有没有一种方法可以定义一种类型,即:

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

谢谢

如果我理解正确,您希望从
Interface1
中选择一个值为
Interface2
的属性

可以通过以下方式实现:

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

type MyType = PropertyOfValue<Interface1, Interface2>;
type PropertyOfValue={
[K in keyof T]-?:T[K]扩展V
?K
:从不
}[keyof T];
类型MyType=PropertyOfValue;
用法:

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

interface Interface2 {
  baz: string;
}

type MyType = PropertyOfValue<Interface1, Interface2>; // "bar"
接口1{
foo:string;
bar:接口2;
}
接口2{
baz:字符串;
}
类型MyType=PropertyOfValue;//“酒吧”

这太神奇了。使用属性映射到自身的映射类型| never,然后使用基于它的索引类型,这是我缺少的技巧。