0

I wnat to declare key with index like

interface myType {
        delivery_name1: string;
        delivery_name2: string;
        delivery_name3: string; 
        delivery_name4: string; 
        delivery_name5: string;
        ...n(20)
   }

I tried

  type Index ="1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"  ...
    type delivery_name = `delivery_name${Index}`

interface myType {
    [key: delivery_name]:string;
}

But got error. An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead

How to solve it ?

2
  • 3
    Would this help you? stackoverflow.com/a/51659490/10100812 Commented May 4, 2022 at 6:33
  • @Edwin It is solved, if you want leave an answer I will check it! Commented May 4, 2022 at 8:46

2 Answers 2

2

To add to Edwins excellent answer, if you want to do this n times...

type MakeSeries<T extends number,R extends unknown[] = []> = T extends R['length'] 
? never
: [...R,unknown]['length'] | MakeSeries<T, [...R, unknown]>


type Index = MakeSeries<20> // <-- n times
type delivery_name = `delivery_name${Index}`

type myType = {
    [key in delivery_name]: string;
}
//**
type myType = {
delivery_name1: string;
delivery_name2: string;
delivery_name3: string;
delivery_name4: string;
delivery_name5: string;
delivery_name6: string;
delivery_name7: string;
... 12 more ...;
delivery_name20: string;
**//

}

TypeScript Playground

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

2 Comments

WOOOOW THNAKS!!!
That's really cool!~
0

You cannot use interface for the type in this case. Please use a type instead:

type Index ="1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
type delivery_name = `delivery_name${Index}`

type myType = {
    [key in delivery_name]: string;
}

TypeScript Playground

Reference

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.