EndsWith
问题描述
实现EndsWith<T, U>,接收两个string类型参数,然后判断T是否以U结尾,根据结果返回true或false
例如:
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
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
type cases = [
Expect<Equal<EndsWith<'abc', 'bc'>, true>>,
Expect<Equal<EndsWith<'abc', 'abc'>, true>>,
Expect<Equal<EndsWith<'abc', 'd'>, false>>,
Expect<Equal<EndsWith<'abc', 'ac'>, false>>,
Expect<Equal<EndsWith<'abc', ''>, true>>,
Expect<Equal<EndsWith<'abc', ' '>, false>>,
]
// ============= Your Code Here =============
// 答案
type EndsWith<T extends string, U extends string> = T extends `${infer F}${U}` ? true : false;
和上一道题一样的思路。
这段代码定义了一个名为EndsWith的类型操作符,它接受两个类型参数T和U,并返回一个类型为boolean的类型。这个操作符的实现原理是使用infer类型推断来确定T是否以U结尾。
具体来说,EndsWith操作符会尝试将T和U连接成一个字符串,然后检查这个字符串是否等于T。如果等于,那么T就满足EndsWith操作符的条件,返回true;否则,返回false。