Search code examples
typescriptgenericstypestype-conversiontypescript-generics

Separate type when using generics in TypeScript


I have an enam and an associated union type

export enum StorageTypeNames {
    User = "user",
    LoadSettings = "loadSettings",
    InitInfo = "isInit",
}

type StorageType = 
    | { name: StorageTypeNames.User, data: 'User' | 'Admin' | 'Amother' }
    | { name: StorageTypeNames.LoadSettings, data?: string[] }
    | { name: StorageTypeNames.InitInfo, data: boolean };

I use this association in my class:

export class StorageHelper {

  static getData<K extends StorageTypeNames>(type: K): **Extract<StorageType, { name: K }>['data'] | null;**

    static getData(type: StorageTypeNames) {
            let data: string | null = null;
            data = localStorage.getItem(type);
            return data ? JSON.parse(data) : null;
        }
}  

I want to move the selected(boldet) part to a separate type, but there is a problem with generic K

When trying to move to a separate type, i get error:

type ExtractedType = Extract<StorageType, { name: K }>['data'] | null
//*error Cannot find name 'K'

The problem in type variable "К" What i wnat to get

please tell me how to make the selected part into a separate type and use it in other places: simple ex.: test playground thank you in advance!


Solution

  • You are trying to make a generic type, but you forgot to make it generic

    type ExtractedType<K> = Extract<StorageType, { name: K }>['data'] | null
    //                ^^^ MAKE IT GENERIC
    

    playground That's all. Have a good day.