1

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;
1
  • I don't have an answer for you, but something that might help is the io-ts library. github.com/gcanti/io-ts. I currently use this to validate data coming from the client (from JSON, like your example) to coerce them into real domain models that conform to a strict interface. This could help you. Commented Nov 13, 2021 at 15:00

1 Answer 1

2

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
>;
Sign up to request clarification or add additional context in comments.

Comments

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.