Skip to content

Commit

Permalink
fix(tags): typeScript < 4.7 compatibility (fixes #1227)
Browse files Browse the repository at this point in the history
  • Loading branch information
Anber committed Apr 24, 2023
1 parent dbe250b commit d2ee54e
Showing 1 changed file with 23 additions and 11 deletions.
34 changes: 23 additions & 11 deletions packages/tags/src/utils/validateParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,34 @@ export type ParamConstraints =
| [...ParamConstraint[]]
| [...ParamConstraint[], '...'];

// ParamMapping maps each ParamName to its corresponding Param type.
type ParamMapping = {
[K in ParamName]: Extract<Param, readonly [K, ...unknown[]]>; // For each ParamName K, extract the corresponding Param type.
};

// GetParamByName returns the Param type based on the input type T.
type GetParamByName<T> = T extends '*'
? Param
: T extends (infer TNames extends ParamName)[]
? Extract<Param, readonly [TNames, ...unknown[]]>
: T extends ParamName
? Extract<Param, readonly [T, ...unknown[]]>
: never;
? Param // If T is '*', return Param type.
: T extends keyof ParamMapping // If T is a key in ParamMapping (i.e., a ParamName).
? ParamMapping[T] // Return the corresponding Param type from ParamMapping.
: T extends Array<infer TNames> // If T is an array of names.
? TNames extends ParamName // If TNames is a ParamName.
? Extract<Param, readonly [TNames, ...unknown[]]> // Return the corresponding Param type.
: never // If TNames is not a ParamName, return never.
: never; // If T is none of the above, return never.

// MapParams iteratively maps the input ParamConstraints to their corresponding Param types.
export type MapParams<
TNames extends ParamConstraints,
TRes extends Param[] = []
> = TNames extends [infer THead, ...infer TTail extends ParamConstraints]
? THead extends '...'
? [...TRes, ...Params]
: MapParams<TTail, [...TRes, GetParamByName<THead>]>
: TRes;
> = TNames extends [infer THead, ...infer TTail] // If TNames is a non-empty tuple.
? THead extends '...' // If the first element in the tuple is '...'.
? [...TRes, ...Params] // Append all Params to the result tuple.
: MapParams<
Extract<TTail, ParamConstraints>, // Extract the remaining ParamConstraints.
[...TRes, GetParamByName<Extract<THead, ParamName | '*' | ParamName[]>>] // Append the mapped Param to the result tuple and recurse.
>
: TRes; // If TNames is an empty tuple, return the result tuple.

export function isValidParams<T extends ParamConstraints>(
params: Params,
Expand Down

0 comments on commit d2ee54e

Please sign in to comment.