Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

59
Views
Map a union to a string literal union of the type names

I have a type like this (in this case, the user would be a custom interface):

export type ArgumentTypes = string | number | boolean | user;

now, I would like to have a type of

export type ArgumentTypeNames = "string" | "number" | "boolean" | "user";

I've tried to search around myself for a while, but I have not been able to find a way to get the name. I tried to do ${ArgumentTypes} but that didn't work.

I'm pretty new to advanced types ( Mapped, conditional, and so on ) so I would love an explanation of the answer, or of potential solutions.

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

AFAIK, as of today's version of TypeScript, you can't do that without an explicit mapping of string to "string", number to "number" etc. existing somewhere in your program. The mapping might look like this:

interface TypeMapping {
  string: string;
  number: number;
  boolean: boolean;
  user: user;
}

However, not all is lost. You could make this mapping the source of truth, and derive other types from it:

type ArgumentTypeNames = keyof TypeMapping;
type ArgumentTypes = TypeMapping[ArgumentTypeNames];

Try it.

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs