我可以在 TypeScript 中切片文字类型吗
Can I slice literal type in TypeScript
在 TypeScript 中,当我想编辑文字类型时,它可以工作。
type Old = "helloWorld"
// ^? "helloWorld"
type New = `${Old}New`
// ^? "helloWorldNew"
但是我该怎么做呢
type Old = "helloWorld"
// ^? "helloWorld"
type New = Slice<"helloWorld",5> // < Is it possible
// ^? "World"
ts 中没有 Slice,但拆分是否符合您的需求?
type Split<S extends string, D extends string> =
string extends S ? string[] :
S extends '' ? [] :
S extends `${infer T}${D}${infer U}` ? [T, ...Split<U, D>] : [S];
第 1 行声明了两个参数,为简洁起见,我们将使用单个字符。
S 代表要拆分的字符串,D 是分隔符。这个
line 确保它们都是字符串。
第 2 行检查字符串是否为文字,通过检查是否为一般字符串
可以从输入字符串扩展。如果是这样,return 一个字符串数组。我们
无法使用 non-literal 字符串。
第 3 行检查字符串是否为空,如果是 return 一个空元组
type S2 = Split<"", "."> // string[]
type S3 = Split<"1.2", "."> // ['1', '2']
type S4 = Split<"1.2.3", "."> // ['1', '2', '3']
在 TypeScript 中,当我想编辑文字类型时,它可以工作。
type Old = "helloWorld"
// ^? "helloWorld"
type New = `${Old}New`
// ^? "helloWorldNew"
但是我该怎么做呢
type Old = "helloWorld"
// ^? "helloWorld"
type New = Slice<"helloWorld",5> // < Is it possible
// ^? "World"
ts 中没有 Slice,但拆分是否符合您的需求?
type Split<S extends string, D extends string> =
string extends S ? string[] :
S extends '' ? [] :
S extends `${infer T}${D}${infer U}` ? [T, ...Split<U, D>] : [S];
第 1 行声明了两个参数,为简洁起见,我们将使用单个字符。 S 代表要拆分的字符串,D 是分隔符。这个 line 确保它们都是字符串。
第 2 行检查字符串是否为文字,通过检查是否为一般字符串 可以从输入字符串扩展。如果是这样,return 一个字符串数组。我们 无法使用 non-literal 字符串。
第 3 行检查字符串是否为空,如果是 return 一个空元组
type S2 = Split<"", "."> // string[]
type S3 = Split<"1.2", "."> // ['1', '2']
type S4 = Split<"1.2.3", "."> // ['1', '2', '3']