模板文字类型Typescript repeat

模板文字类型Typescript repeat,typescript,Typescript,是否可以使用模板文本类型构建重复?例如: type Hex = 'a' | 'b' | 'c'| ...; type Id = `${Hex}${Hex}...` // Here I want to say Id is N hex long. 原则上,TS 4.1中的递归条件类型可以实现这一点: type Decrement = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] type RepeatString<S extends string, N

是否可以使用模板文本类型构建重复?例如:

type Hex = 'a' | 'b' | 'c'| ...;
type Id = `${Hex}${Hex}...` // Here I want to say Id is N hex long. 

原则上,TS 4.1中的递归条件类型可以实现这一点:

type Decrement = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
type RepeatString<S extends string, N extends number> =
    N extends 1 ? S :
    `${S}${RepeatString<S, Decrement[N]>}`
这就避免了使用
减量来手动计算数字范围


您希望的具体类型是什么?你能逐字加上吗?因为
${Hex}${Hex}…
生成所有的联合类型对
type T11 = Decrement[5] // 4
type T12 = RepeatString<"foo", 3> // "foofoofoo"
type T13 = RepeatString<Hex, 3> // "aaa" | "aab" | ... | "ccb" | "ccc"
type RepeatStringAlt<S extends string, N extends number> = RepeatStringAltRec<S, TupleOf<unknown, N>>
type RepeatStringAltRec<S extends string, T extends unknown[]> =
    T["length"] extends 1 ? S : `${S}${RepeatStringAltRec<S, DropFirst<T>>}`
    
type TupleOf<T, N extends number> = N extends N ? number extends N ? T[] : _TupleOf<T, N, []> : never;
type _TupleOf<T, N extends number, R extends unknown[]> = R['length'] extends N ? R : _TupleOf<T, N, [T, ...R]>;
type DropFirst<T extends readonly unknown[]> = T extends readonly [any?, ...infer U] ? U : [...T];

type T23 = RepeatStringAlt<"foo", 3> // "foofoofoo"