题目
中文
实现类型 PercentageParser/^(\+|\-)?(\d*)?(\%)?$/
匹配类型 T。
匹配的结果由三部分组成,分别是:[正负号
, 数字
, 单位
],如果没有匹配,则默认是空字符串。
例如:
type PString1 = '';
type PString2 = '+85%';
type PString3 = '-85%';
type PString4 = '85%';
type PString5 = '85';
type R1 = PercentageParser<PString1>; // expected ['', '', '']
type R2 = PercentageParser<PString2>; // expected ["+", "85", "%"]
type R3 = PercentageParser<PString3>; // expected ["-", "85", "%"]
type R4 = PercentageParser<PString4>; // expected ["", "85", "%"]
type R5 = PercentageParser<PString5>; // expected ["", "85", ""]
English
Implement PercentageParser
According to the /^(\+|\-)?(\d*)?(\%)?$/
regularity to match T and get three matches.
The structure should be: [plus or minus
, number
, unit
]
If it is not captured, the default is an empty string.
For example:
type PString1 = '';
type PString2 = '+85%';
type PString3 = '-85%';
type PString4 = '85%';
type PString5 = '85';
type R1 = PercentageParser<PString1>; // expected ['', '', '']
type R2 = PercentageParser<PString2>; // expected ["+", "85", "%"]
type R3 = PercentageParser<PString3>; // expected ["-", "85", "%"]
type R4 = PercentageParser<PString4>; // expected ["", "85", "%"]
type R5 = PercentageParser<PString5>; // expected ["", "85", ""]
答案
解法一(自己琢磨的)
type PercentageParser<A extends string> = A extends `${infer L extends
| '+'
| '-'}${infer R}`
? [L, PercentageParser<R>[1], PercentageParser<R>[2]]
: A extends `${infer L extends number}${infer R}`
? ['', `${L}${PercentageParser<R>[1]}`, PercentageParser<R>[2]]
: ['', '', A];
解法二(参考的别的解法, 应该优于解法一)
type PercentageParser<
A extends string,
Sign extends '+' | '-' | '' = '',
Mark extends '' | '%' = ''
> = A extends `${infer L extends '+' | '-'}${infer R}`
? PercentageParser<R, L>
: A extends `${infer L}%`
? PercentageParser<L, Sign, '%'>
: [Sign, A, Mark];
标签:Typescript,PercentageParser,extends,体操,expected,type,infer,85
From: https://www.cnblogs.com/laggage/p/type-challenge-percentage-parser.html