[TypeScript] Type Challenges #2688 - StartsWith

40 阅读1分钟

题目描述

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

例如:

type a = StartsWith<'abc', 'ac'> // expected to be false
type b = StartsWith<'abc', 'ab'> // expected to be true
type c = StartsWith<'abc', 'abcd'> // expected to be false

题解

// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'

type cases = [
  Expect<Equal<StartsWith<'abc', 'ac'>, false>>,
  Expect<Equal<StartsWith<'abc', 'ab'>, true>>,
  Expect<Equal<StartsWith<'abc', 'abc'>, true>>,
  Expect<Equal<StartsWith<'abc', 'abcd'>, false>>,
  Expect<Equal<StartsWith<'abc', ''>, true>>,
  Expect<Equal<StartsWith<'abc', ' '>, false>>,
  Expect<Equal<StartsWith<'', ''>, true>>,
]


// ============= Your Code Here =============
type StartsWith<
  T extends string,
  U extends string
> =
  T extends `${U}${infer _}` 
	? true 
	: false;

条件类型

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

    • T extends ${U}${infer _}

      • 如果T可以表示为${U}${infer _},即TU开头,infer _捕获U之后的部分

      • 如果TU开头,返回true

      • 否则,返回false