给定一个接口A
interface A {
foo: string;
bar: boolean;
}
我想派生另一个具有以下属性的接口 B
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>;
}
给定一个接口 A
interface A { foo: string; bar: boolean; }
我想派生另一个具有以下属性的接口 B
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 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 }
}
游乐场的例子
下面到底有什么不适用?您是否遇到编译错误或它在概念上不起作用?
interface B {
[K keyof A]: SomeOtherInterface
}
难道你必须做
interface B<A> {
[K keyof A]: SomeOtherInterface
}
我也想知道拥有像B
这样的类型,其中所有属性都是完全相同的类型的目的是什么?