-
Notifications
You must be signed in to change notification settings - Fork 391
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
「重学TS 2.0 」TS 练习题第三十八题 #58
Comments
// 实现 StartsWith 工具类型,判断字符串字面量类型 T 是否以给定的字符串字面量类型 U 开头,并根据判断结果返回布尔值。具体的使用示例如下所示:
type StartsWith<T extends string, U extends string> = T extends `${U}${infer Rest}` ? true : false;
type S0 = StartsWith<"123", "12">; // true
type S1 = StartsWith<"123", "13">; // false
type S2 = StartsWith<"123", "1234">; // false
// 此外,继续实现 EndsWith 工具类型,判断字符串字面量类型 T 是否以给定的字符串字面量类型 U 结尾,并根据判断结果返回布尔值。具体的使用示例如下所示:
type EndsWith<T extends string, U extends string> = T extends `${infer Head}${U}` ? true : false;
type E0 = EndsWith<"123", "23">; // true
type E1 = EndsWith<"123", "13">; // true
type E2 = EndsWith<"123", "123">; // true |
模板字面量的使用,里面可以直接放string,number等类型 |
type StartsWith<T extends string, U extends string> = T extends `${U}${infer R}`
? true
: false;
type EndsWith<T extends string, U extends string> = T extends `${infer F}${U}`
? true
: false; |
|
type StartsWith<T extends string, U extends string> = T extends `${U}${string}` ? true : false
type S0 = StartsWith<'123', '12'> // true
type S1 = StartsWith<'123', '13'> // false
type S2 = StartsWith<'123', '1234'> // false
type EndsWith<T extends string, U extends string> = T extends `${string}${U}` ? true : false
type E0 = EndsWith<'123', '23'> // true
type E1 = EndsWith<'123', '13'> // false
type E2 = EndsWith<'123', '123'> // true |
type StartsWith<
type S0 = StartsWith<"123", "12">; // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
实现
StartsWith
工具类型,判断字符串字面量类型T
是否以给定的字符串字面量类型U
开头,并根据判断结果返回布尔值。具体的使用示例如下所示:此外,继续实现
EndsWith
工具类型,判断字符串字面量类型T
是否以给定的字符串字面量类型U
结尾,并根据判断结果返回布尔值。具体的使用示例如下所示:The text was updated successfully, but these errors were encountered: