There is this very messy API I want to consume, where the values returned are somewhat inconsistent. I could go over every single entry and try and make a type that would cover it, but this would take a very long time, and I wanted to do so programmatically.
My idea would be to infer the types. Let’s say I receive this array:
const array = [
{
title: "test",
name: "Katy Smith",
},
{
title: ["ACNM", "AAF3"],
name: "Mary Williams,
},
{
title: "test2",
name: { firstName: "John", lastName: "Doe" },
},
];
I would infer the type with typescript or something else, so it would return the inferred type
{
title: string | string[],
name: string | {firstName: string, lastName: string}
}
And then I want to save this so I could use it in my project, like fs.writeFile("type.txt". Type). I’m aware that unfortunately typescript doesn’t exist at runtime, so this would be impossible.
Are there any other ways I could achieve this?
3
Answers
I am unsure about what you are trying to do, but if the issue is related to type errors due to inconsistency in API response, you could set the type of response array as
any[]
or if the response too isn’t consistent and not always an array you could just tryany
.I didn’t fully understand the question but here is a way you could set it up so you could use 1 class for all of your types. But after seeing your last comment Im guessing this is not what you need.
Playground Link
You will need a package of some kind to do this.
A package like QuickType should do the trick.
https://github.com/glideapps/quicktype
I haven’t used it, there are probably others.