Home > Software engineering >  How to Reconvert an interface of values with a wrapper type?
How to Reconvert an interface of values with a wrapper type?

Time:01-07

I have an interface.

interface MyInterface {
    carrot: string;
    apple: { isObj: true };
}

and I'd like to transform it with a wrapper type that will match the interface key and value exactly. (e.g. wrap with Promise/Observable/Function)

// My attempt..
type WrapWithPromise = Record<keyof MyInterface, Promise<MyInterface[keyof MyInterface]>>

const myObj = {} as WrapWithPromise // Duct Type Test
myObj.apple.then(data => {
    console.log(data) // shows as "string | { isObj: boolean; }"
})

The issue with the above code is that each of the keys have a union of the possible value types instead of a direct type mapped. string | { isObj: boolean }

How can I get the keys to match the first interface exactly instead of a union type? E.g. apple key to be recognized as { isObj: boolean; } only instead of a union of

string | { isObj: boolean }

CodePudding user response:

Use a mapped type to map each key to a type based on that key

type WrapWithPromise = {
  [K in keyof MyInterface]: Promise<MyInterface[K]>
}

Playground

  • Related