Rya*_*ugh 13
没有办法将字符串长度指定为类型。
如果您有一个有限的国家/地区代码列表,您可以编写一个字符串文字类型:
type CountryCode = 'US' | 'CN' | 'CA' | ...(lots of others);
Run Code Online (Sandbox Code Playgroud)
vye*_*nkv 13
实际上是可以做到的
// tail-end recursive approach: returns the type itself to reuse stack of previous call
type LengthOfString<
S extends string,
Acc extends 0[] = []
> = S extends `${string}${infer $Rest}`
? LengthOfString<$Rest, [...Acc, 0]>
: Acc["length"];
type IsStringOfLength<S extends string, Length extends number> = LengthOfString<S> extends Length ? true : false
type ValidExample = IsStringOfLength<'json', 4>
type InvalidExapmple = IsStringOfLength<'xml', 4>
Run Code Online (Sandbox Code Playgroud)
谢谢
归档时间: |
|
查看次数: |
7212 次 |
最近记录: |