跳到主要内容

Trim Right

介绍

实现 TrimRight<T> ,它接收确定的字符串类型并返回一个新的字符串,其中新返回的字符串删除了原字符串结尾的空白字符串。

ts
type Trimed = TrimRight<' Hello World '> // 应推导出 ' Hello World'
ts
type Trimed = TrimRight<' Hello World '> // 应推导出 ' Hello World'
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type TrimRight<S extends string> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<TrimRight<'str'>, 'str'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TrimRight<'str '>, 'str'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TrimRight<'str '>, 'str'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TrimRight<' str '>, ' str'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TrimRight<' foo bar \n\t '>, ' foo bar'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TrimRight<''>, ''>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TrimRight<'\n\t '>, ''>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
ts
/* _____________ Your Code Here _____________ */
 
type TrimRight<S extends string> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<TrimRight<'str'>, 'str'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TrimRight<'str '>, 'str'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TrimRight<'str '>, 'str'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TrimRight<' str '>, ' str'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TrimRight<' foo bar \n\t '>, ' foo bar'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TrimRight<''>, ''>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TrimRight<'\n\t '>, ''>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
type TrimRight<S extends string> = S extends `${infer F}${' '|'\n'|'\t'}` ? TrimRight<F> : S;
 
ts
type TrimRight<S extends string> = S extends `${infer F}${' '|'\n'|'\t'}` ? TrimRight<F> : S;
 
view more solutions