Implement
Trim<T>which takes an exact string type and returns a new string with the whitespace from both ends removed.
實現 Trim<T>,該泛型接受一個精確的字串類型,並返回一個去除兩端空白的新字串。
type trimmed = Trim<' Hello World '> // expected to be 'Hello World'
接下來,你的任務是讓下面的type cases測試通過:
type cases = [
Expect<Equal<Trim<'str'>, 'str'>>,
Expect<Equal<Trim<' str'>, 'str'>>,
Expect<Equal<Trim<' str'>, 'str'>>,
Expect<Equal<Trim<'str '>, 'str'>>,
Expect<Equal<Trim<' str '>, 'str'>>,
Expect<Equal<Trim<' \n\t foo bar \t'>, 'foo bar'>>,
Expect<Equal<Trim<''>, ''>>,
Expect<Equal<Trim<' \n\t '>, ''>>,
]
從以下幾個方向來思考:
infer 關鍵字從泛型中推導出型別。infer 來推斷剩餘的字串內容。解法:
type Space = '\t' | '\n' | ' '
type Trim<S extends string> =
S extends `${Space}${infer R}` | `${infer R}${Space}` ? Trim<R> : S
細節分析:
Space 是我們定義的字串聯合類型,包含空白字符(空格、\t、\n)。這些是我們要移除的字符。
Trim<S> 檢查字串是否符合以下兩種模式之一:
R。R。Trim<R> 來繼續移除空白字符,直到字串不再符合條件為止,最後返回結果。額外補充:
Escape sequences are special combinations of characters that start with a backslash () followed by another character to represent things like tabs, newlines, and other non-printable or special characters in a string. For example:
\t represents a tab.\n represents a newline.\\ represents a literal backslash.\" represents a double quote.
這樣,我們就能順利通過測試啦 🎉 😭 🎉
本次介紹了 Trim 的實作,下一關會挑戰 Capitalize,期待再相見!