0

Let's imagine that we have the object with following keys: (The number of keys always is 30)

const options = {
  "option1": 582, // Random value
  "option1": 6,
  "option3": 123,
  "option4": 3812,
  // ...
  "option30": 482,
}

So, one of the way to declare an interface for this object would be the following example:

interface IProperties {
  "option1": number,
  "option2": number,
  "option3": number,
  "option4": number,
  // ...
  "option30": number
} 

But what if there are will be more options than 30? (1000 for example) It will be silly to write an interface with 1000 keys.

So, which is the best solution for this situation? How we can generate keys dynamically in interface instead of hardcode? May be we can generates the keys in loop?

2 Answers 2

5

One approach would be to define a type Numbers that is a union of all numbers in the range you want to include (eg: 1 - 30). This union still requires exhaustively listing the full range of numbers but allows defining a more dynamic Properties type.

Then, using a tempalte literal to define all the possible keys.

// The non-unique prefix for all option keys
type Prefix = "option"

// Exhaustive list of all options
type Numbers = 0 | 1 | 2 | 3 | 4 | 5

// Combine the prefix and numbers using a template literal
type Keys = `${Prefix}${Numbers}`

// Equivalent to:
//
// type Keys = "option0" | "option1" | "option2" | "option3" | "option4" | "option5"

type Properties = {
    [Key in Keys]: number
}

// Equivalent to:
//
// type Properties = {
//     option0: number;
//     option1: number;
//     option2: number;
//     option3: number;
//     option4: number;
//     option5: number;
// }

TypeScript playground

Assuming the Numbers are "fixed" you could use a piece of JavaScript in your console to create the full Numbers type union.

[...Array(30).keys()].map(key => key + 1).join(" | ")
// "1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30"

This could then be copy and pasted as the value for the Numbers type.

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

Comments

0

You are looking for Record<T,K>

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.