跳到主要内容

E

介绍

实现EndsWith<T, U>,接收两个string类型参数,然后判断T是否以U结尾,根据结果返回truefalse

例如:

ts
type a = EndsWith<'abc', 'bc'> // expected to be true
type b = EndsWith<'abc', 'abc'> // expected to be true
type c = EndsWith<'abc', 'd'> // expected to be false
ts
type a = EndsWith<'abc', 'bc'> // expected to be true
type b = EndsWith<'abc', 'abc'> // expected to be true
type c = EndsWith<'abc', 'd'> // expected to be false
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type EndsWith<T extends string, U extends string> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<EndsWith<'abc', 'bc'>, true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<EndsWith<'abc', 'abc'>, true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<EndsWith<'abc', 'd'>, false>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<EndsWith<'abc', 'ac'>, false>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<EndsWith<'abc', ''>, true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<EndsWith<'abc', ' '>, false>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
ts
/* _____________ Your Code Here _____________ */
 
type EndsWith<T extends string, U extends string> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<EndsWith<'abc', 'bc'>, true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<EndsWith<'abc', 'abc'>, true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<EndsWith<'abc', 'd'>, false>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<EndsWith<'abc', 'ac'>, false>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<EndsWith<'abc', ''>, true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<EndsWith<'abc', ' '>, false>>,
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 EndsWith<T extends string, U extends string> = T extends `${infer _}${U}` ? true : false;
 
ts
type EndsWith<T extends string, U extends string> = T extends `${infer _}${U}` ? true : false;
 
view more solutions