0

In my code I import an object that also containing type for each property, for example(simplified):

const obj= {
  OUTPUT: ["port","number"],
}

which means OUTPUT:{port:number;}

how can i extract the second constant in the array to represent the type of the first constant in the array?

any help will be very appreciated,thanks in advance.

I've already tried:

const string2Type = (str: string): string | number | object => {
  const tmp: any = null;
  switch (str) {
    case "number":
      return tmp as number;
    case "string":
      return tmp as string;
    case "object":
      return tmp as object;
  }
};

const obj = {
  OUTPUT: ["port","number"],
};

const OUTPUTtype = string2Type(obj.OUTPUT[1]) 

const OUTPUT = obj.OUTPUT[0] as typeof OUTPUTtype
// but here OUTPUT: string | number | object instead of number... How can i fix this?

(of course this wouldn't work because switch case is runtime (in javascript) and typescript is compiled language, but I can't get this to work)

similar question:

most close is Typescript: How to convert a string to a type but i don't see how it can solve my specific issue.

Eliav Louski
  • 3,593
  • 2
  • 28
  • 52

0 Answers0