我如何使用 TypeScript 类型获取字符串的长度?
我正在尝试获取字符串的长度作为数字:
type Length = LengthOfString<"hello">
// ^? should be 5
我不确定从哪里开始。我要如何实现这个?
(我正在尝试更多地了解 TypeScript 的类型系统——我并不是将其应用到 JS 代码中)
答案#1
一种方法是使用模板字面量字符串来拆分字符串的每个字符。我们为可以检索的每个字符向元组L添加一些元素。
type LengthOfString<T extends string, L extends any[] = []> =
T extends `${string}${infer R}`
? LengthOfString<R, [...L, string]>
: L["length"]
当没有剩余字符时,我们返回 L 的 length
结果 :
type Length = LengthOfString<"hello">
// ^? 5
操场
