Is it possible to create typescript types from string values?
Something like this
const typeName = 'number';
type myType = typeName;
const x: myType = 5;
Is it possible to create typescript types from string values?
Something like this
const typeName = 'number';
type myType = typeName;
const x: myType = 5;
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/
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.
typeof typeName part? Isn't it supposed to be string in this case?