Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create AllUnionFields type #997

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ export type {ArraySplice} from './source/array-splice';
export type {ArrayTail} from './source/array-tail';
export type {SetFieldType} from './source/set-field-type';
export type {Paths} from './source/paths';
export type {AllUnionFields} from './source/all-union-fields';
export type {SharedUnionFields} from './source/shared-union-fields';
export type {SharedUnionFieldsDeep} from './source/shared-union-fields-deep';
export type {IsNull} from './source/is-null';
Expand Down
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ Click the type names for complete docs.
- [`Paths`](source/paths.d.ts) - Generate a union of all possible paths to properties in the given object.
- [`SharedUnionFields`](source/shared-union-fields.d.ts) - Create a type with shared fields from a union of object types.
- [`SharedUnionFieldsDeep`](source/shared-union-fields-deep.d.ts) - Create a type with shared fields from a union of object types, deeply traversing nested structures.
- [`AllUnionFields`](source/all-union-fields.d.ts) - Create a type with all fields from a union of object types.
- [`DistributedOmit`](source/distributed-omit.d.ts) - Omits keys from a type, distributing the operation over a union.
- [`DistributedPick`](source/distributed-pick.d.ts) - Picks keys from a type, distributing the operation over a union.
- [`And`](source/and.d.ts) - Returns a boolean for whether two given types are both true.
Expand Down
86 changes: 86 additions & 0 deletions source/all-union-fields.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import type {NonRecursiveType, ReadonlyKeysOfUnion, ValueOfUnion} from './internal';
import type {KeysOfUnion} from './keys-of-union';
import type {SharedUnionFields} from './shared-union-fields';
import type {Simplify} from './simplify';
import type {UnknownArray} from './unknown-array';

/**
Create a type with all fields from a union of object types.

Use-cases:
- You want a safe object type where each key exists in the union object.

@example
```
import type {AllUnionFields} from 'type-fest';

type Cat = {
name: string;
type: 'cat';
catType: string;
};

type Dog = {
name: string;
type: 'dog';
dogType: string;
};

function displayPetInfo(petInfo: Cat | Dog) {
// typeof petInfo =>
// {
// name: string;
// type: 'cat';
// catType: string;
// } | {
// name: string;
// type: 'dog';
// dogType: string;
// }

console.log('name: ', petInfo.name);
console.log('type: ', petInfo.type);

// TypeScript complains about `catType` and `dogType` not existing on type `Cat | Dog`.
console.log('animal type: ', petInfo.catType ?? petInfo.dogType);
}

function displayPetInfo(petInfo: AllUnionFields<Cat | Dog>) {
// typeof petInfo =>
// {
// name: string;
// type: 'cat' | 'dog';
// catType?: string;
// dogType?: string;
// }

console.log('name: ', petInfo.name);
console.log('type: ', petInfo.type);

// No TypeScript error.
console.log('animal type: ', petInfo.catType ?? petInfo.dogType);
}
```

@see SharedUnionFields

@category Object
@category Union
*/
export type AllUnionFields<Union> =
Extract<Union, NonRecursiveType | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown> | UnknownArray> extends infer SkippedMembers
? Exclude<Union, SkippedMembers> extends infer RelevantMembers
?
| SkippedMembers
| Simplify<
SharedUnionFields<RelevantMembers> &
{
readonly [P in ReadonlyKeysOfUnion<RelevantMembers>]?: ValueOfUnion<RelevantMembers, P & KeysOfUnion<RelevantMembers>>;
} & {
[
P in Exclude<KeysOfUnion<RelevantMembers>, ReadonlyKeysOfUnion<RelevantMembers> | keyof RelevantMembers>
]?: ValueOfUnion<RelevantMembers, P>;
}
>
: never
: never;
34 changes: 34 additions & 0 deletions source/internal/object.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type {Simplify} from '../simplify';
import type {UnknownArray} from '../unknown-array';
import type {IsEqual} from '../is-equal';
import type {KeysOfUnion} from '../keys-of-union';
import type {FilterDefinedKeys, FilterOptionalKeys} from './keys';
import type {NonRecursiveType} from './type';
Expand Down Expand Up @@ -122,3 +123,36 @@ type IndexSignature = HomomorphicPick<{[k: string]: unknown}, number>;
export type HomomorphicPick<T, Keys extends KeysOfUnion<T>> = {
[P in keyof T as Extract<P, Keys>]: T[P]
};

/**
Extract all possible values for a given key from a union of object types.

@example

type Statuses = ValueOfUnion<{ id: 1, status: "open" } | { id: 2, status: "closed" }, "status">;
//=> "open" | "closed"
*/
export type ValueOfUnion<Union, Key extends KeysOfUnion<Union>> =
Union extends unknown ? Key extends keyof Union ? Union[Key] : never : never;

/**
Extract all readonly keys from a union of object types.

@example
type User = {
readonly id: string;
name: string;
};

type Post = {
readonly id: string;
readonly author: string;
body: string;
};

type ReadonlyKeys = ReadonlyKeysOfUnion<User | Post>;
//=> "id" | "author"
*/
export type ReadonlyKeysOfUnion<Union> = Union extends unknown ? keyof {
[Key in keyof Union as IsEqual<{[K in Key]: Union[Key]}, {readonly [K in Key]: Union[Key]}> extends true ? Key : never]: never
} : never;
1 change: 1 addition & 0 deletions source/shared-union-fields.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ function displayPetInfo(petInfo: SharedUnionFields<Cat | Dog>) {
```

@see SharedUnionFieldsDeep
@see AllUnionFields

@category Object
@category Union
Expand Down
184 changes: 184 additions & 0 deletions test-d/all-union-fields.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
import {expectType} from 'tsd';
import type {AllUnionFields, Simplify} from '../index';
import type {NonRecursiveType} from '../source/internal';

type TestingType = {
function: () => void;
record: Record<
string,
{
propertyA: string;
}
>;
object: {
subObject: {
subSubObject: {
propertyA: string;
};
};
};
string: string;
union: 'test1' | 'test2';
number: number;
boolean: boolean;
date: Date;
regexp: RegExp;
symbol: symbol;
null: null;
undefined: undefined;
optional?: boolean | undefined;
readonly propertyWithKeyword: boolean;
map: Map<string, {propertyA: string; propertyB: string}>;
set: Set<string>;
objectSet: Set<{propertyA: string; propertyB: string}>;
};

declare const normal: AllUnionFields<
TestingType | {string: string; number: number; foo: any}
>;
expectType<Simplify<
{
string: string;
number: number;
foo?: any;
} & Partial<Omit<TestingType, 'string' | 'number'>>
>>(normal);

declare const unMatched: AllUnionFields<TestingType | {foo: any}>;
expectType<Simplify<
{
foo?: any;
} & Partial<TestingType>
>>(unMatched);

declare const number: AllUnionFields<TestingType | {number: number; foo: any}>;
expectType<Simplify<{
number: number;
foo?: any;
} & Partial<Omit<TestingType, 'number'>>
>>(number);

declare const string: AllUnionFields<TestingType | {string: string; foo: any}>;
expectType<Simplify<{
string: string;
foo?: any;
} & Partial<Omit<TestingType, 'string'>>
>>(string);

declare const boolean: AllUnionFields<TestingType | {boolean: boolean; foo: any}>;
expectType<Simplify<{
boolean: boolean;
foo?: any;
} & Partial<Omit<TestingType, 'boolean'>>
>>(boolean);

declare const date: AllUnionFields<TestingType | {date: Date; foo: any}>;
expectType<Simplify<{
date: Date;
foo?: any;
} & Partial<Omit<TestingType, 'date'>>
>>(date);

declare const regexp: AllUnionFields<TestingType | {regexp: RegExp; foo: any}>;
expectType<Simplify<{
regexp: RegExp;
foo?: any;
} & Partial<Omit<TestingType, 'regexp'>>
>>(regexp);

declare const symbol: AllUnionFields<TestingType | {symbol: symbol; foo: any}>;
expectType<Simplify<{
symbol: symbol;
foo?: any;
} & Partial<Omit<TestingType, 'symbol'>>
>>(symbol);

declare const null_: AllUnionFields<TestingType | {null: null; foo: any}>;
expectType<Simplify<{
null: null;
foo?: any;
} & Partial<Omit<TestingType, 'null'>>
>>(null_);

declare const undefined_: AllUnionFields<TestingType | {undefined: undefined; foo: any}>;
expectType<Simplify<{
undefined: undefined;
foo?: any;
} & Partial<Omit<TestingType, 'undefined'>>
>>(undefined_);

declare const optional: AllUnionFields<TestingType | {optional: string; foo: any}>;
expectType<Simplify<{
optional?: string | boolean | undefined;
foo?: any;
} & Partial<Omit<TestingType, 'optional'>>
>>(optional);

declare const propertyWithKeyword: AllUnionFields<TestingType | {readonly propertyWithKeyword: string; foo: any}>;
expectType<Simplify<{
readonly propertyWithKeyword: boolean | string;
foo?: any;
} & Partial<Omit<TestingType, 'propertyWithKeyword'>>
>>(propertyWithKeyword);

declare const map: AllUnionFields<TestingType | {map: Map<string, {propertyA: string}>; foo: any}>;
expectType<Simplify<{
map: TestingType['map'] | Map<string, {propertyA: string}>;
foo?: any;
} & Partial<Omit<TestingType, 'map'>>
>>(map);

declare const set: AllUnionFields<TestingType | {set: Set<number>; foo: any}>;
expectType<Simplify<{
set: TestingType['set'] | Set<number>;
foo?: any;
} & Partial<Omit<TestingType, 'set'>>
>>(set);

declare const moreUnion: AllUnionFields<TestingType | {string: string; number: number; foo: any} | {string: string; bar: any}>;
expectType<Simplify<{
string: string;
foo?: any;
bar?: any;
} & Partial<Omit<TestingType, 'string'>>
>>(moreUnion);

declare const union: AllUnionFields<TestingType | {union: {a: number}}>;
expectType<Simplify<{
union: 'test1' | 'test2' | {a: number};
} & Partial<Omit<TestingType, 'union'>>
>>(union);

declare const unionWithOptional: AllUnionFields<{a?: string; foo: number} | {a: string; bar: string}>;
expectType<{
a?: string;
foo?: number;
bar?: string;
}>(unionWithOptional);

declare const mixedKeywords: AllUnionFields<{readonly a: string; b: number} | {a: string; readonly b: string}>;
expectType<{
readonly a: string;
readonly b: string | number;
}>(mixedKeywords);

declare const mixedKeywords2: AllUnionFields<{readonly a: string; b: number} | {a: string; readonly b: string} | {readonly c: number}>;
expectType<{
readonly a?: string;
readonly b?: string | number;
readonly c?: number;
}>(mixedKeywords2);

// Non-recursive types
expectType<Set<string> | Map<string, string>>({} as AllUnionFields<Set<string> | Map<string, string>>);
expectType<string[] | Set<string>>({} as AllUnionFields<string[] | Set<string>>);
expectType<NonRecursiveType>({} as AllUnionFields<NonRecursiveType>);

// Mix of non-recursive and recursive types
expectType<{a: string | number; b?: true} | undefined>({} as AllUnionFields<{a: string} | {a: number; b: true} | undefined>);
expectType<RegExp | {test: string}>({} as AllUnionFields<RegExp | {test: string}>);
expectType<RegExp | null | {test: string | number; foo?: any}>({} as AllUnionFields<RegExp | null | {test: string} | {test: number; foo: any}>);

// Boundary types
expectType<any>({} as AllUnionFields<any>);
expectType<never>({} as AllUnionFields<never>);
27 changes: 27 additions & 0 deletions test-d/internal/readonly-keys-of-union.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {expectType} from 'tsd';
import type {ReadonlyKeysOfUnion} from '../../source/internal';

declare const test1: ReadonlyKeysOfUnion<{readonly a: 1; b: 2}>;
expectType<'a'>(test1);

declare const test2: ReadonlyKeysOfUnion<{readonly a: 1; b?: 2} | {readonly c?: 3; d: 4}>;
expectType<'a' | 'c'>(test2);

declare const test3: ReadonlyKeysOfUnion<{readonly a: 1; b?: 2} | {readonly c?: 3; d: 4} | {readonly c: 5} | {d: 6}>;
expectType<'a' | 'c'>(test3);

// Returns `never` if there's no readonly key
declare const test4: ReadonlyKeysOfUnion<{a: 1; b?: 2} | {c?: 3; d: 4}>;
expectType<never>(test4);

// Works with index signatures
declare const test5: ReadonlyKeysOfUnion<{readonly [x: string]: number; a: 1} | {readonly [x: symbol]: number; a: 2}>;
expectType<string | number | symbol>(test5);

// Works with arrays
declare const test7: ReadonlyKeysOfUnion<readonly string[] | readonly [number, number]>;
expectType<number | typeof Symbol.unscopables | '0' | '1' | 'length'>(test7);

// Works with functions
declare const test8: ReadonlyKeysOfUnion<(() => void) | {(): void; readonly a: 1}>;
expectType<'a'>(test8);
Loading
Loading