Búsqueda de sitios web

TypeScript: Derivar interfaz de otra interfaz reutilizando las claves pero no los valores


Dada una interfaz A

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

Quiero derivar otra interfaz B con las siguientes propiedades

interface B {
  foo: SomeOtherInterface;
  bar: SomeOtherInterface;
}

¿Es posible hacerlo?

Hasta ahora puedo extraer las claves mediante type X=keyof A, pero no puedo derivar la interfaz B con esas claves.

Desafortunadamente, lo siguiente NO funciona:

interface B {
  [K keyof A]: SomeOtherInterface
}

Pregunta extra: ¿Qué pasa con la interfaz C?

interface C {
  foo: SomeOtherGenericInterface<string>;
  bar: SomeOtherGenericInterface<boolean>;
}

Respuesta #1

Dada una interfaz A

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

Quiero derivar otra interfaz B con las siguientes propiedades

interface B {
  foo: SomeOtherInterface;
  bar: SomeOtherInterface;
}

Puedes hacerlo así:

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" }
}

Pregunta extra: ¿Qué pasa con la interfaz C?

interface C {
  foo: SomeOtherGenericInterface<string>;
  bar: SomeOtherGenericInterface<boolean>;
}

Creo que esto está haciendo lo que quieres:

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 }
}

Ejemplo en el patio de recreo

Respuesta #2

¿Qué exactamente no funciona con lo siguiente? ¿Obtienes un error de compilación o simplemente no funciona conceptualmente?

interface B {
    [K keyof A]: SomeOtherInterface
}

¿podría ser que tengas que hacer

interface B<A> {
    [K keyof A]: SomeOtherInterface
}

También me pregunto cuál es el objetivo de tener un tipo como B donde todas las propiedades son del mismo tipo exacto.