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

TypeScript: how to map interface to custom data types

I have the following types:

interface USER {
    email: string;
    age: number;
}
interface SCORES {
    likes: number;
    followers: number;
}

and then composite state as shown below:

interface UserStats {
    user: USER;
    stats: SCORES;
}

Now I get a payload which looks like this:

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

{type: 'user', values: {email:"abc@gmail.com",age: 21}}
or
{type: 'stats', values: {likes:20,followers: 21}}

While destructuring the above payload, I need to assign its type such that it covers both the cases, something like:

type payloadKeyTypes = 'user' | 'stats'
type configPayload = USER | SCORES
interface payloadType {
    [payloadKeyTypes]: configPayLoad
}

But this says: A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type

How do I go for resolving it?

>Solution :

Using union type as an index signature in interface is forbidden. However, since typescript 4.4 you can use symbols and template literal strings.

In this particular case, worth using type Record because it allows you to use unions:

interface USER {
    email: string;
    age: number;
}

interface SCORES {
    likes: number;
    followers: number;
}

interface UserStats {
    user: USER;
    stats: SCORES;
}

type payloadKeyTypes = 'user' | 'stats'

type configPayload = USER | SCORES

type payloadType = Record<payloadKeyTypes, configPayload> 

Playground

Also, be aware that there is a naming convention in typescript. All types/interfaces/enums should be Capitalized and CamelCased. However, it is only a convention.

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