1

I'm getting a data in my react component props which is all of same type but different variables.

Is there any way so I can just need to define all the type variable in one line.

interface IcarouselProps {
  img1: string
  img2: string
  img3: string
  img4: string
  img5: string
  img6: string
  heading1: string,
  heading2: string,
  heading3: string,
  heading4: string,
  heading5: string,
  heading6: string,
}
1
  • You can do this: [key: string]: string if you just want a dictionary, but it won't assure you that you have keys in the form of img{x} and header{x} Commented Dec 1, 2021 at 7:26

1 Answer 1

1

On TS4.1 and above you can write:

type IcarouselProps = Record<`${'img' | 'heading'}${number}`, string>;

But this will allow accessing properties not in range (1..6) too. So to make type-checking more stricter, you can do something like this:

type Enumerate<N extends number, Result extends Array<unknown> = []> = Result['length'] extends N
  ? Result[number]
  : Enumerate<N, [...Result, Result['length']]>;

type IcarouselProps = Record<`${'img' | 'heading'}${Exclude<Enumerate<7>, 0>}`, string>;

// the above will work for any value <46 in place of 7 in TS4.1-4 and <1000 in TS4.5

// `Exclude<Enumerate<TO>, Enumerate<FROM>>` will generate integer range from `FROM` to `TO - 1` both inclusive.

Run this on Typescript Playground.

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.