Home > database >  Create custom type from object by extracting types of object's values
Create custom type from object by extracting types of object's values

Time:05-11

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

CodePudding user response:

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

  • Related