Home > Back-end >  Typescript object key with index
Typescript object key with index

Time:05-05

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 ?

CodePudding user response:

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

CodePudding user response:

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

  • Related