diff --git a/src/types/objects.ts b/src/types/objects.ts index c519e58..1a32712 100644 --- a/src/types/objects.ts +++ b/src/types/objects.ts @@ -102,6 +102,15 @@ export type DiffKeys = Diff, Keys>; */ export type HasKey = K extends Keys ? 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 + // 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 // ------------- diff --git a/test/objects/UnionKeys.test.ts b/test/objects/UnionKeys.test.ts new file mode 100644 index 0000000..2ac768e --- /dev/null +++ b/test/objects/UnionKeys.test.ts @@ -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; + type expected = 'w' | 'x' | 'y' | 'z'; + + assert(t); + assert(t); +});