A tiny set of utility types for working with unions.
npm i gist:5d48bb3b92fa02cd9eb34ee87d3c7050
Get a union of all keys from all members of a union.
import { UnionKey } from "union-types";
type Foo = { a: string; b: number };
type Bar = { a: boolean; b: bigint; c: string };
type FoobarKey = keyof (Foo | Bar);
// => "a" | "b" ❌ missing "c"
type FoobarKey = keyof (Foo & Bar);
// => string | number | symbol ❌ intersecting incompatible types returns never
type FoobarKey = UnionKey<Foo | Bar>;
// => "a" | "b" | "c" ✅
Get a union of all keys that are optional or missing in at least one member of a union.
import { OptionalUnionKey } from "union-types";
type Foo = { a: string; b?: number };
type Bar = { a: boolean; b: bigint; c: string };
type optionalFoobarKey = OptionalUnionKey<Foo | Bar>;
// => "b" | "c"
// "c" is included because it doesn't exist in Foo
Get a union of all keys that are required in all members of a union.
import { RequiredUnionKey } from "union-types";
type Foo = { a: string; b?: number };
type Bar = { a: boolean; b: bigint; c: string };
type RequiredFoobarKey = RequiredUnionKey<Foo | Bar>;
// => "a"
Get a union of all values for a key from all members of a union.
import { UnionValue } from "union-types";
type Foo = { a: string; b?: number };
type Bar = { a: boolean; b: bigint; c: string };
type FooBar_C = UnionValue<Foo | Bar, "c">;
// => string | undefined
Merge a union or intersection of objects into a single type.
import { Merge } from "union-types";
type GetBlockOptions = {
includeTransactions?: boolean;
} & (
| {
blockHash: string;
blockNumber?: undefined;
blockTag?: undefined;
}
| {
blockHash?: undefined;
blockNumber: bigint;
blockTag?: undefined;
}
| {
blockHash?: undefined;
blockNumber?: undefined;
blockTag: string;
}
)
type Merged = Merge<GetBlockOptions>;
// {
// includeTransactions?: boolean | undefined;
// blockHash?: string | undefined;
// blockNumber?: bigint | undefined;
// blockTag?: string | undefined;
// }