I am getting some JSON objects from a network call, of the shape:
{
timestamp: "1636814680595",
price: "$1",
...manyOtherKeys
}
All values are strings.
I'd like to create an interface based on an array of the expected keys. From this:
const expectedKeys = ['timestamp', 'price', ...]
I would like to programmatically generate the type (or interface):
type ExpectedType {
timestamp: string,
price: string
}
Is there an easy way to do that? For now, all I can think of is the following, which seems contrived:
// I did not find a way to start from an array and reduce it to this object
// while preserving the type. I'm okay starting with this object instead of
// an array of string.
const objectWithExpectedShape = {
timestamp: '',
price: '',
}
type ExpectedType = typeof objectWithExpectedShape;
CodePudding user response:
What you want is only possible if the expectedKeys
is static - if you hard-code it. (If they're dynamically generated and not present in the source code, it's impossible, because TypeScript types only operate on what exists at compile-time - at runtime, you're only left with plain JavaScript)
Define the array as const
so it doesn't get widened to string[]
, and then you can make a Record composed of the keys (the array items) and string
.
const expectedKeys = ['timestamp', 'price'] as const;
type ExpectedType = Record<
typeof expectedKeys[number],
string
>;