[TypeScript] Type Challenges #2693 - EndsWith

16 阅读1分钟

题目描述

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

例如:

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 `${string}${U}` 
	? true 
	: false

条件类型

type EndsWith<
  T extends string,
  U extends string
> =
  T extends `${string}${U}` 
	? true 
	: false
  • 条件判断:

    • T extends ${string}${U}

      • 如果T可以表示为${string}${U},即TU结尾,返回true

      • 否则,返回false