type-fest
Version:
A collection of essential TypeScript types
85 lines (69 loc) • 2.5 kB
TypeScript
import type {UnknownCollection} from './unknown-collection.d.ts';
import type {OmitIndexSignature} from './omit-index-signature.d.ts';
import type {NonRecursiveType, SimplifyObject} from './internal/index.d.ts';
import type {IsNever} from './is-never.d.ts';
import type {SharedUnionFieldsDeep} from './shared-union-fields-deep.d.ts'; // For `@link`
import type {AllUnionFields} from './all-union-fields.d.ts'; // For `@link`
/**
Create a type with shared fields from a union of object types.
Use-cases:
- You want a safe object type where each key exists in the union object.
- You want to focus on the common fields of the union type and don't want to have to care about the other fields.
@example
```
import type {SharedUnionFields} from 'type-fest';
type Cat = {
name: string;
type: 'cat';
catType: string;
};
type Dog = {
name: string;
type: 'dog';
dogType: string;
};
type PetInfo = SharedUnionFields<Cat | Dog>;
//=> {name: string; type: 'cat' | 'dog'}
function displayPetInfo(petInfo: Cat | Dog) {
// typeof petInfo =>
// {
// name: string;
// type: 'cat';
// catType: string; // Needn't care about this field, because it's not a common pet info field.
// } | {
// name: string;
// type: 'dog';
// dogType: string; // Needn't care about this field, because it's not a common pet info field.
// }
// The `petInfo` type is complex and has some unnecessary fields.
console.log('name:', petInfo.name);
console.log('type:', petInfo.type);
}
function displayPetInfoWithSharedUnionFields(petInfo: SharedUnionFields<Cat | Dog>) {
// typeof petInfo =>
// {
// name: string;
// type: 'cat' | 'dog';
// }
// The `petInfo` type is simple and clear.
console.log('name:', petInfo.name);
console.log('type:', petInfo.type);
}
```
@see {@link SharedUnionFieldsDeep}
@see {@link AllUnionFields}
@category Object
@category Union
*/
export type SharedUnionFields<Union> =
Extract<Union, NonRecursiveType | UnknownCollection> extends infer SkippedMembers
? Exclude<Union, SkippedMembers> extends infer RelevantMembers
? // eslint-disable-line @stylistic/operator-linebreak
| SkippedMembers
| (IsNever<RelevantMembers> extends true
? never
// Keep shared index domains and declared fields separately so index signatures cannot hide known properties.
: SimplifyObject<Pick<RelevantMembers, keyof RelevantMembers> & Pick<RelevantMembers, keyof OmitIndexSignature<RelevantMembers> & keyof RelevantMembers>>)
: never
: never;
export {};