Home > Net >  TypeScript: how to map interface to custom data types
TypeScript: how to map interface to custom data types

Time:01-03

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:

{type: 'user', values: {email:"[email protected]",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?

CodePudding user response:

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.

  • Related