Typescript - How to narrow generic mapped types in a function?

159 Views Asked by At

I have 3 user types as declared below

declare enum UserType {
    Admin = "Admin",
    Tester = "Tester",
    Customer = "Customer",
}

type AdminParams = { ... }
class Admin {
    constructor(parameters: AdminParams) {}
}

type TesterParams = { ... }
class Tester {
    constructor(parameters: TesterParams) {}
}

type CustomerParams = { ... }
class Customer {
    constructor(parameters: CustomerParams) {}
}

And I have UserFactory class which generates user instance based on given type

// Params based on user Type
type UserTypeParamsMap = {
    [UserType.Admin]: AdminParams;
    [UserType.Tester]: TesterParams;
    [UserType.Customer]: CustomerParams;
};
type UserParam<T extends keyof UserTypeParamsMap> = UserTypeParamsMap[T];

// Class based on user type
type UserTypeInstanceMap = {
    [UserType.Admin]: Admin;
    [UserType.Tester]: Tester;
    [UserType.Customer]: Customer;
};
type UserInstance<T extends keyof UserTypeInstanceMap> = UserTypeInstanceMap[T];

// Factory
export class UserFactory {
    public static createNew = async <T extends keyof UserTypeParamsMap>(userType: T, params: UserParam<T>): Promise<UserInstance<T>> => {
        ...
    }
}

Function signature is correct when I input different type of users function_user_type_admin function_user_type_tester

But in the function it can not narrow params, whenever I check it in if statement enter image description here

How can I narrow it to be specific mapped type using given userType?

Typescript version: 4.6.3

Expected: params to be narrowed to specific type

Playground Link

0

There are 0 best solutions below