我读到了类型记录4.5beta的博客文章,作者实现了一个TrimLeft实用程序类型来显示Tail-Recursion Elimination on Conditional Types,所以我决定实现一个Trim实用程序类型(为了学习目的),我的问题是,你会做什么,你会怎么做?
type Trim<T extends string> =
T extends
`${infer RestOne} ${infer RestTwo}`
? Trim<`${RestOne}${RestTwo}`>
: T extends ` ${infer RestThree} ${infer RestFour}`
? Trim<`${RestThree}${RestFour}`>
: T extends ` ${infer RestFive} ${infer RestSix} `
? Trim<`${RestFive}${RestSix}`>
: T extends `${infer RestSeven} ${infer RestEight} `
? Trim<`${RestSeven}${RestEight}`>
: T;
type TestOne = Trim<" foo"> ; // "foo"
type TestTwo = Trim< " foo "> ; // "foo"
type TestThree = Trim<" foo bar "> ; // "foobar"
type TestThree = Trim<" foo bar "> ; // "foobar"
type TestFour = Trim<"foo bar ">; // "foobar"
basically, it trims out all space in `Trim<T>`发布于 2021-10-18 07:57:32
考虑一下这个例子:
type Separator = ' ';
type Trim<T extends string, Acc extends string = ''> =
(T extends `${infer Char}${infer Rest}`
? (Char extends Separator
? Trim<Rest, Acc>
: Trim<Rest, `${Acc}${Char}`>)
: (T extends ''
? Acc
: never)
)
type TestOne = Trim<" foo">; // "foo"
type TestTwo = Trim<" foo ">; // "foo"
type TestThree = Trim<" foo bar ">; // "foobar"
type TestThree2 = Trim<" foo bar ">; // "foobar"
type TestFour = Trim<"foo bar ">; // "foobar"Trim -遍历整个字符串。如果它找到Separator (空空间),它只是省略它,并将Acc与不带分隔符的部分字符串连接起来。
https://stackoverflow.com/questions/69610786
复制相似问题