Skip to content

Commit

Permalink
Exact: Fix usage with recursive types and unions (#949)
Browse files Browse the repository at this point in the history
  • Loading branch information
abrenneke committed Sep 8, 2024
1 parent 30b8e22 commit 91f6d39
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
15 changes: 8 additions & 7 deletions source/exact.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,14 @@ onlyAcceptNameImproved(invalidInput); // Compilation error
@category Utilities
*/
export type Exact<ParameterType, InputType> =
// If the parameter is a primitive, return it as is immediately to avoid it being converted to a complex type
ParameterType extends Primitive ? ParameterType
// If the parameter is an unknown, return it as is immediately to avoid it being converted to a complex type
: IsUnknown<ParameterType> extends true ? unknown
// If the parameter is a Function, return it as is because this type is not capable of handling function, leave it to TypeScript
: ParameterType extends Function ? ParameterType
: IsEqual<ParameterType, InputType> extends true ? ParameterType
// Before distributing, check if the two types are equal and if so, return the parameter type immediately
IsEqual<ParameterType, InputType> extends true ? ParameterType
// If the parameter is a primitive, return it as is immediately to avoid it being converted to a complex type
: ParameterType extends Primitive ? ParameterType
// If the parameter is an unknown, return it as is immediately to avoid it being converted to a complex type
: IsUnknown<ParameterType> extends true ? unknown
// If the parameter is a Function, return it as is because this type is not capable of handling function, leave it to TypeScript
: ParameterType extends Function ? ParameterType
// Convert union of array to array of union: A[] & B[] => (A & B)[]
: ParameterType extends unknown[] ? Array<Exact<ArrayElement<ParameterType>, ArrayElement<InputType>>>
// In TypeScript, Array is a subtype of ReadonlyArray, so always test Array before ReadonlyArray.
Expand Down
16 changes: 16 additions & 0 deletions test-d/exact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -537,3 +537,19 @@ import type {Exact, Opaque} from '../index';
// @ts-expect-error
function_(withExcessSurname);
}

// Spec - recursive type with union
// @see https://github.com/sindresorhus/type-fest/issues/948
{
type A = {
a: Expected;
};
type B = {
b: string;
};
type Expected = A | B;

const function_ = <T extends Exact<Expected, T>>(arguments_: T) => arguments_;

function_({} as Expected);
}

0 comments on commit 91f6d39

Please sign in to comment.