Skip to content

Commit

Permalink
fix: issue sindresorhus#788 added ifEqual guard
Browse files Browse the repository at this point in the history
  • Loading branch information
harsh-pesto committed Jan 7, 2024
1 parent eb96609 commit 5995215
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.d.ts
Expand Up @@ -99,6 +99,7 @@ export type {IsAny} from './source/is-any';
export type {IfAny} from './source/if-any';
export type {IsNever} from './source/is-never';
export type {IfNever} from './source/if-never';
export type {IfEqual} from './source/if-equal';
export type {IsUnknown} from './source/is-unknown';
export type {IfUnknown} from './source/if-unknown';
export type {ArrayIndices} from './source/array-indices';
Expand Down
24 changes: 24 additions & 0 deletions source/if-equal.d.ts
@@ -0,0 +1,24 @@
import type { IsEqual } from './is-equal';

/**
* An if-else-like type that resolves depending on whether the two given types are equal.
*
* @see {@link IsEqual}
*
* @example
* ```
* import type { IfEqual } from 'type-fest';
*
* type Result1 = IfEqual<string, string, 'Equal', 'NotEqual'>;
* //=> 'Equal'
*
* type Result2 = IfEqual<string, number, 'Equal', 'NotEqual'>;
* //=> 'NotEqual'
* ```
*
* @category Type Guard
* @category Utilities
*/
export type IfEqual<A, B, TypeIfEqual = true, TypeIfNotEqual = false> = (
IsEqual<A, B> extends true ? TypeIfEqual : TypeIfNotEqual
);
18 changes: 18 additions & 0 deletions test-d/if-equal.ts
@@ -0,0 +1,18 @@
import { expectType, expectError } from 'tsd';
import type { IfEqual } from '../index';

// `IfEqual` should return `true`/`false` if only `A` and `B` are specified
expectType<IfEqual<string, string>>(true);
expectType<IfEqual<string, number>>(false);

// `IfEqual` with custom types for equal or not equal cases
expectType<IfEqual<string, string, 'Equal', 'NotEqual'>>('Equal');
expectType<IfEqual<string, number, 'Equal', 'NotEqual'>>('NotEqual');

// `IfEqual` should correctly handle complex types
expectType<IfEqual<{ a: number }, { a: number }>>(true);
expectType<IfEqual<{ a: number }, { b: number }>>(false);

// Missing generic parameters
expectError<IfEqual<string>>(undefined);
expectError<IfEqual>(undefined);

0 comments on commit 5995215

Please sign in to comment.