2

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?

3
  • 2
    You should use type Record instead of interface. See here. Btw, there is no numeric type - only number Commented Jan 3, 2022 at 10:45
  • As for using symbols and template strings as index signature in interface you can see docs and PR Commented Jan 3, 2022 at 10:49
  • 2
    Hey Thanks, would you mind adding it as answer so that I could accept it and close this? Commented Jan 3, 2022 at 10:49

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.