Fill
, a common JavaScript function, now let us implement it with types. Fill<T, N, Start?, End?>
, as you can see,Fill
accepts four types of parameters, of which T
and N
are required parameters, and Start
and End
are optional parameters. The requirements for these parameters are: T
must be a tuple
, N
can be any type of value, Start
and End
must be integers greater than or equal to 0.
type exp = Fill<[1, 2, 3], 0> // expected to be [0, 0, 0]
type PlusOne<T extends number, C extends unknown[] = []> = C['length'] extends T
? [...C, unknown]['length']
: PlusOne<T, [...C, unknown]>
type Fill<
T extends unknown[],
N,
Start extends number = 0,
End extends number = T['length'],
P extends number = 0 // set a pointer, init with 0
> = Start extends End // Stop when Start = End
? T
: T extends [infer F, ...infer RT]
? P extends Start
? [N, ...Fill<RT, N, PlusOne<Start>, End, PlusOne<P>>] // Replace the value when Pointer = Start, increasing value by 1
: [F, ...Fill<RT, N, Start, End, PlusOne<P>>] // No need to replace F, increase P
: [];
标签:Typescript,End,parameters,Start,Medium,extends,68,type,Fill From: https://www.cnblogs.com/Answer1215/p/16826968.html