'Typescript - How to narrow generic mapped types in a function?
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


But in the function it can not narrow params, whenever I check it in if statement

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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
