Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
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 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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!