【发布时间】:2021-10-15 13:14:38
【问题描述】:
我的这段代码非常适合使用 as const 的静态数组
type ScaleKeys<A extends readonly unknown[]> = `${keyof A & `${number}`}x`;
const spacing = [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4] as const;
type SpaceKeys = ScaleKeys<typeof spacing>; // works great with a static array
const a: SpaceKeys = '0x';
但是必须静态声明一个大的静态数组并不是很好。
是否可以用动态数组来做到这一点:
我试过了:
type ScaleKeys<A extends readonly unknown[]> = `${keyof A & `${number}`}x`;
const b: ReadonlyArray<number> = Array.from({ length: 20 });
type C = ScaleKeys<typeof b> // not sure if this is even possible
这是一个playground,上面有。
【问题讨论】:
-
您对
ScaleKeys<typeof b>有什么期望?${number}px? -
@captain-yossarian 字符串联合'1x' | '2x' | '3x' .... 等到 '20x'
-
一旦
b只是一个ReadonlyArray<number>,编译器不知道它有多长。您可以告诉它C是ScaleKeys<TupleLen<20>>用于适当定义的TupleLen类型,例如this code,但编译器无法跟踪20你写的代码。如果我提供的代码满足您的需求,我可以写一个答案;否则请在minimal reproducible example 中描述失败的用例。
标签: typescript tuples