Typescript類型體操 - StartsWith

題目

中文

實現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

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;

在線演示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章