0

I am trying to create a type from this object:

export const AppStore = {
    LoggedInUserState: {
        stateName: "LoggedInUserState",
        stateModel: LoggedInUserStateModel,
    },
    JwtDecodedUserState: {
        stateName: "JwtDecodedUserState",
        stateModel: JwtDecodedUserStateModel,
    },
    LoaderState: {
        stateName: "LoaderState",
        stateModel: LoaderStateModel,
    },
} as const;

I want the type to be an object whose keys are exactly stateName and values will be exactly stateModel

The resulted type I want:

{
    "LoggedInUserState": LoggedInUserStateModel,
    "JwtDecodedUserState": JwtDecodedUserStateModel,
    "LoaderState": LoaderStateModel,
}

Solution I've tried:

export type TAppStore = typeof AppStore;
export type StateKeys = keyof TAppStore;

export type AppState = {
    [stateKey: TAppStore[StateKeys]["stateName"]]: TAppStore[StateKeys]["stateModel"];
};

But I'm getting error: TS1337: An index signature parameter type cannot be a union type. Consider using a mapped object type instead.

The error underlines the stateKey in my solution as incorrect.

Any help will be appreciated. Thanks

1 Answer 1

1

You should try it like this:

export type TAppStore = typeof AppStore;

export type AppState = {
    -readonly [
      K in keyof TAppStore as TAppStore[K]["stateName"]
    ]: TAppStore[K]["stateModel"]
}

Playground

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

3 Comments

Thankyou, your solution worked. I have never used the - symbol that you have used before readonly keyword. Can you explain or guide me to some sources that explain this? Thankyou
You declared the object with as const which results in lots of readonly modifiers in the type definition. When using mapped types, the readonly modifier stays for each property. When you want to remove readonly you can put - readonly in front of the index signature of the mapped type. and voila: the readonly is gone

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.