0

Is it possible to create typescript types from string values?
Something like this

const typeName = 'number';
type myType = typeName;
const x: myType = 5;
2
  • What's your use case? Commented Jul 29, 2019 at 13:37
  • @Michael, I get the types from an api response, and need to dynamically generate interfaces using those. Commented Jul 29, 2019 at 14:24

2 Answers 2

2

Dynamically generating types for an API at runtime isn't going to be very useful, at that point it's too late and you may as well be using any

It sounds like what you want to do is generate types for the API as a pre-build step.

There's a few options for this, one is to write a specification of the API using a format such as openapi3 and use a code generation tool to generate the API client / glue code. This is an approach I've taken on a number of projects, and it works fairly well but you do have to fight the generator at times.

There are also tools that will generate JSON schema from a JSON blob, and in turn generate typescript types from JSON schema. Again they aren't perfect, but often this can be a quick and easy way to scaffold types for an API, that you can then manually refine.

Ref: https://openapi.tools/ https://quicktype.io/typescript/

Sign up to request clarification or add additional context in comments.

Comments

1

Not really possible to go from a type name to a type in typescript, even for built-in types. You might consider creating a mapping interface between names and types. Then going from name to type would require a simple type index query:

interface TypeMap {
    number: number,
    string: string,
    boolean: boolean,
    // etc
}
const typeName = 'number';
type myType = TypeMap[typeof typeName];
const x: myType = 5;

Edit We need typeof typeName (instead of typeName in TypeMap[typeof typeName]) because type index queries work with types (not with values such as variables). We can however get the type of any variable using the typeof type operator.

2 Comments

This makes sense. Thanks. Can you clarify the typeof typeName part? Isn't it supposed to be string in this case?
@HaykSafaryan added an explanation, let me know if it helps :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.