【发布时间】:2021-07-14 23:09:40
【问题描述】:
我正在尝试为包含逗号分隔值的字符串定义 Typescript 模板文字。我可以让这个定义真正递归和通用吗?
请参阅this typescript playground 以试用此案例。
每个逗号分隔值代表一个排序顺序,如height asc。该字符串应定义一个顺序(包括主要、次要、第三等),根据有效字段名称和两个可能的顺序"asc" 和"desc" 的联合,可能包含无限多个排序级别,按照逗号分隔示例代码中的示例。
下面的实现最多可以处理 4 个排序顺序,但案例 5 表明它并不是真正的递归。当前扩展 (2x2) 的数量最多仅包含 4 个可能的值,因此碰巧处理了我尝试的初始情况。
const FIELD_NAMES = [
"height",
"width",
"depth",
"time",
"amaze",
] as const;
const SORT_ORDERS = [
"asc",
"desc",
] as const;
type Field = typeof FIELD_NAMES[number];
type Order = typeof SORT_ORDERS[number];
type FieldOrder = `${Field} ${Order}`
type Separated<S extends string> = `${S}${""|`, ${S}`}`;
type Sort = Separated<Separated<FieldOrder>>;
/** SUCCESS CASES */
const sort1:Sort = "height asc"; //compiles
const sort2:Sort = "height asc, depth desc"; //compiles
const sort3:Sort = "height asc, height asc, height asc"; //compiles
const sort4:Sort = "height asc, width asc, depth desc, time asc"; //compiles
const sort5:Sort = "height asc, width asc, depth desc, time asc, amaze desc"; //SHOULD compile but doesn't
/** FAILURE CASES */
const sort6:Sort = "height"; //doesn't compile
const sort7:Sort = "height asc,"; //doesn't compile
const sort8:Sort = ""; //doesn't compile
我不能再增加这个模板文字的“arity”了,因为尝试像下面那样做 2x2x2 会导致 Expression produces a union type that is too complex to represent
type Sort = Separated<Separated<Separated<FieldOrder>>>;
是否可以定义模板文字来处理一般情况?
【问题讨论】:
标签: typescript csv sorting recursion template-literals