以下代码可用于enum在TypeScript中创建:
enum e {
hello = 1,
world = 2
};
Run Code Online (Sandbox Code Playgroud)
并且可以通过以下方式访问这些值:
e.hello;
e.world;
Run Code Online (Sandbox Code Playgroud)
如何创建enum带字符串值?
enum e {
hello = "hello", // error: cannot convert string to e
world = "world" // error
};
Run Code Online (Sandbox Code Playgroud) 我正在尝试为包含逗号分隔值的字符串定义 Typescript 模板文字。我能让这个定义真正递归和通用吗?
请参阅此打字稿游乐场来尝试该案例。
每个逗号分隔的值代表一个排序顺序,例如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"; …Run Code Online (Sandbox Code Playgroud)