Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Reconvert an interface of values with a wrapper type?

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 }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 }

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading