题目
中文
实现StartsWith<T, U>
,接收两个 string 类型参数,然后判断T
是否以U
开头,根据结果返回true
或false
例如:
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
English
Implement StartsWith<T, U>
which takes two exact string types and returns whether T
starts with U
For example
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
答案
递归(第一时间想到的, 不是最优解)
type StartsWith<
T extends string,
U extends string
> = T extends `${infer L}${infer R}`
? U extends `${infer UL}${infer UR}`
? UL extends L
? StartsWith<R, UR>
: false
: true
: U extends ''
? true
: false;
最优解
type StartsWith<T extends string, U extends string> = T extends `${U}${any}`
? true
: false;
标签:StartsWith,Typescript,false,true,extends,体操,expected,type
From: https://www.cnblogs.com/laggage/p/type-challenge-starts-with.html