type-fest
Version:
A collection of essential TypeScript types
120 lines (90 loc) • 4.09 kB
TypeScript
import type {KeysOfUnion} from './keys-of-union.d.ts';
import type {ApplyDefaultOptions} from './apply-default-options.d.ts';
import type {RequireNone} from './require-none.d.ts';
/**
Filter out keys from an object.
Returns `never` if `Exclude` is strictly equal to `Key`.
Returns `never` if `Key` extends `Exclude`.
Returns `Key` otherwise.
@example
```
type Filtered = Filter<'foo', 'foo'>;
//=> never
```
@example
```
type Filtered = Filter<'bar', string>;
//=> never
```
@example
```
type Filtered = Filter<'bar', 'foo'>;
//=> 'bar'
```
@see {Except}
*/
type Filter<KeyType, ExcludeType> = Exclude<KeyType, ExcludeType>;
export type ExceptOptions = {
/**
Disallow assigning non-specified properties.
Note that any omitted properties in the resulting type will be present in autocomplete as `undefined`.
@default false
*/
requireExactProps?: boolean;
};
type DefaultExceptOptions = {
requireExactProps: false;
};
/**
Create a type from an object type without certain keys.
We recommend setting the `requireExactProps` option to `true`.
This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically.
This type was proposed to the TypeScript team, which declined it, saying they prefer that libraries implement stricter versions of the built-in types ([microsoft/TypeScript#30825](https://github.com/microsoft/TypeScript/issues/30825#issuecomment-523668235)).
Note: For a generic conditional type, TypeScript only accepts the keys that all its branches share, because it does not know which branch applies. To remove a key that only some branches have, intersect it with `KeysOfUnion`, as in `Except<Conditional<T>, 'key' & KeysOfUnion<Conditional<T>>>`. When the resolved type does not have the key, nothing is removed.
@example
```
import type {Except} from 'type-fest';
type Foo = {
a: number;
b: string;
};
type FooWithoutA = Except<Foo, 'a'>;
//=> {b: string}
// @ts-expect-error
const fooWithoutA: FooWithoutA = {a: 1, b: '2'};
// errors: 'a' does not exist in type '{ b: string; }'
type FooWithoutB = Except<Foo, 'b', {requireExactProps: true}>;
//=> {a: number} & {b?: never}
// @ts-expect-error
const fooWithoutB: FooWithoutB = {a: 1, b: '2'};
// errors at 'b': Type 'string' is not assignable to type 'undefined'.
// The `Omit` utility type doesn't work when omitting specific keys from objects containing index signatures.
// Consider the following example:
type UserData = {
[metadata: string]: string;
email: string;
name: string;
role: 'admin' | 'user';
};
// `Omit` clearly doesn't behave as expected in this case:
type PostPayload = Omit<UserData, 'email'>;
//=> {[x: string]: string; [x: number]: string}
// In situations like this, `Except` works better.
// It simply removes the `email` key while preserving all the other keys.
type PostPayloadFixed = Except<UserData, 'email'>;
//=> {[x: string]: string; name: string; role: 'admin' | 'user'}
```
@category Object
*/
export type Except<ObjectType, KeysType extends KeysOfUnion<ObjectType>, Options extends ExceptOptions = {}> =
_Except<ObjectType, KeysType, ApplyDefaultOptions<ExceptOptions, DefaultExceptOptions, Options>>;
// The mapped type is homomorphic, so it distributes over a union `ObjectType` by itself, and a generic `ObjectType` stays assignable to it. Only `requireExactProps` needs an explicit distribution, so that each member gets its own keys.
type _Except<ObjectType, KeysType, Options extends Required<ExceptOptions>> =
Options['requireExactProps'] extends true
? ObjectType extends unknown
? {[KeyType in keyof ObjectType as Filter<KeyType, KeysType>]: ObjectType[KeyType]} & RequireNone<KeysType & keyof ObjectType>
: never
: {
[KeyType in keyof ObjectType as Filter<KeyType, KeysType>]: ObjectType[KeyType];
};
export {};