TypeScript:通过重新使用键而不是值,从其他接口派生接口

TypeScript:通过重新使用键而不是值,从其他接口派生接口,typescript,Typescript,给定一个接口A interface A { foo: string; bar: boolean; } interface A { foo: string; bar: boolean; } 我想派生另一个具有以下属性的接口B interface B { foo: SomeOtherInterface; bar: SomeOtherInterface; } interface B { foo: SomeOtherInterface; bar: SomeOther

给定一个接口A

interface A {
  foo: string;
  bar: boolean;
}
interface A {
  foo: string;
  bar: boolean;
}
我想派生另一个具有以下属性的接口B

interface B {
  foo: SomeOtherInterface;
  bar: SomeOtherInterface;
}
interface B {
  foo: SomeOtherInterface;
  bar: SomeOtherInterface;
}
有可能吗

到目前为止,我能够通过
type X=keyof A
提取密钥,但是我无法用这些密钥导出接口B

不幸的是,以下不起作用:

interface B {
  [K keyof A]: SomeOtherInterface
}
奖金问题: 接口C呢

interface C {
  foo: SomeOtherGenericInterface<string>;
  bar: SomeOtherGenericInterface<boolean>;
}
interface C {
  foo: SomeOtherGenericInterface<string>;
  bar: SomeOtherGenericInterface<boolean>;
}
接口C{
foo:其他通用接口;
条形图:其他通用界面;
}

以下哪项不适用?您是否遇到编译错误,或者它在概念上不起作用

interface B {
    [K keyof A]: SomeOtherInterface
}
是不是你必须这么做

interface B<A> {
    [K keyof A]: SomeOtherInterface
}
接口B{
[K keyof A]:SomeOtherInterface
}
我还想知道,拥有像
B
这样的类型的目的是什么,其中所有属性都是完全相同的类型

给定一个接口A

interface A {
  foo: string;
  bar: boolean;
}
interface A {
  foo: string;
  bar: boolean;
}
我想派生另一个具有以下属性的接口B

interface B {
  foo: SomeOtherInterface;
  bar: SomeOtherInterface;
}
interface B {
  foo: SomeOtherInterface;
  bar: SomeOtherInterface;
}
您可以这样做:

interface A {
  foo: string;
  bar: boolean;
}

interface SomeOtherInterface {
    other: string;
}

type B = {
  [K in keyof A]: SomeOtherInterface
}

// Example
const b: B = {
    foo: { other: "foo" },
    bar: { other: "bar" }
}
附加问题:接口C如何

interface C {
  foo: SomeOtherGenericInterface<string>;
  bar: SomeOtherGenericInterface<boolean>;
}
interface C {
  foo: SomeOtherGenericInterface<string>;
  bar: SomeOtherGenericInterface<boolean>;
}
接口C{
foo:其他通用接口;
条形图:其他通用界面;
}
我认为这是你想要的:

interface SomeOtherGenericInterface<T> {
    value: T;
}

type DerivedTypeWithSomeOtherGenericValues<T, V extends { [K in keyof T]: any }> = {
    [K in keyof T]: SomeOtherGenericInterface<V[K]>
}

type C = DerivedTypeWithSomeOtherGenericValues<A, { foo: string, bar: number }>;

// Example
const c: C = {
    foo: { value: "foo" },
    bar: { value: 123 }
}
接口其他通用接口{
值:T;
}
类型DerivedTypewithsomeOtherGenericValue={
[K in keyof T]:其他通用接口
}

类型C=具有其他通用值的衍生类型。谢谢你的回答!正是
[K in keyof T]
发挥了神奇的作用。是否也可以反转派生接口B中的可选和必需属性?因此,如果在A
foo
是必需的,而
bar
不是必需的,那么在接口B中是否可以有
foo
可选和
bar
必需?我认为不可能像您所描述的那样将它们完全颠倒,但是您可以通过使用
来控制派生类型是否具有可选性。是的,我知道将它们都设置为可选。不幸的是,在我的例子中,我需要精确的倒过来的值。感谢您抽出时间回答问题!:)谢谢你的回答。不幸的是,它不能像您建议的那样工作,因为接口不能以这种方式创建。它只适用于类型和
[K in typeof A]
。亚伦在那里做了正确的事情。