Skip to content

Commit

Permalink
feat: add UnionKeys
Browse files Browse the repository at this point in the history
  • Loading branch information
Retsam committed Jan 8, 2019
1 parent 96320a2 commit 9810171
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/types/objects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,15 @@ export type DiffKeys<T, U> = Diff<Keys<T>, Keys<U>>;
*/
export type HasKey<T, K extends keyof any> = K extends Keys<T> ? True : False;

/**
* @param T the union to get the keys of
* @returns a union containing all the keys of members of `T`
*/
export type UnionKeys<T>
// Using a conditional here, so that it distributes over members of the union
// See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types
= T extends any ? keyof T : never;

// -------------
// Manipulations
// -------------
Expand Down
16 changes: 16 additions & 0 deletions test/objects/UnionKeys.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import test from 'ava';
import { assert } from '../helpers/assert';

import { AllKeys, UnionKeys } from '../../src';

test('Can get all keys between objects in a union', t => {
type a = { w: number, x: string };
type b = { x: number, z: boolean };
type c = { y: boolean, z: string };

type got = UnionKeys<a | b | c>;
type expected = 'w' | 'x' | 'y' | 'z';

assert<got, expected>(t);
assert<expected, got>(t);
});

0 comments on commit 9810171

Please sign in to comment.