type-fest
Version:
A collection of essential TypeScript types
158 lines (134 loc) • 7.2 kB
TypeScript
import type {MatchingKey} from '../matching-key.d.ts';
import type {IsEqual} from '../is-equal.d.ts';
import type {IsNever} from '../is-never.d.ts';
import type {StringToNumber} from '../string-to-number.d.ts';
import type {OmitIndexSignature} from '../omit-index-signature.d.ts';
import type {PickIndexSignature} from '../pick-index-signature.d.ts';
import type {DefinedKeyFilter, OptionalKeyFilter} from './keys.d.ts';
import type {KeyToString} from './string.d.ts';
/**
Flatten an object type. This is the plain definition `Simplify` had before it started returning a function, a class constructor, or a branded primitive as is.
Internal types use this instead of `Simplify`, because they only flatten object types they built themselves, where any call signature is already dropped or handled separately and no branded primitive can appear, so they do not need that check. Use `Simplify` if the input can be a function, a class constructor, or a branded primitive. Keeping the check out of them avoids its cost in every type that flattens its result, and avoids the risk of "excessively deep" errors in user code, which a conditional in `Simplify` once caused for types like `SetRequired`. See https://github.com/sindresorhus/type-fest/issues/436.
*/
export type SimplifyObject<Type> = {[KeyType in keyof Type]: Type[KeyType]} & {};
/**
Create an object type with the given key `<Key>` and value `<Value>`.
It will copy the prefix and optional status of the same key from the given object `CopiedFrom` into the result.
@example
```
type A = BuildObject<'a', string>;
//=> {a: string}
// Copy `readonly` and `?` from the key `a` of `{readonly a?: any}`
type B = BuildObject<'a', string, {readonly a?: any}>;
//=> {readonly a?: string}
```
*/
export type BuildObject<Key extends PropertyKey, Value, CopiedFrom extends object = {}> =
Key extends unknown // Keep separate objects for a union of keys.
// Look up both forms of a numeric key before copying its modifiers.
? IsNever<MatchingKey<CopiedFrom, Key>> extends true
? {[_ in Key]: Value}
: Pick<{[_ in keyof CopiedFrom]: Value}, MatchingKey<CopiedFrom, Key>>
: never;
/**
Prepare object properties for `Jsonify` by filtering omitted keys and replacing unions with `undefined` with optional properties.
It also removes the properties that `JSON.stringify` drops: symbol keys, properties that are only `undefined`, required properties that are only a symbol, and properties whose type includes a function. A `never` property is removed too. An `any` or `unknown` property is kept as it is, including whether it is optional.
@example
```
type User = {
firstName: string;
lastName: string | undefined;
};
type OptionalizedUser = JsonifyObjectProperties<User>;
//=> {
// firstName: string;
// lastName?: string;
// }
```
*/
export type JsonifyObjectProperties<T extends object> = SimplifyObject<
// Each key is filtered on its own in the `as` clause. Filtering `keyof T` as a union would merge a literal key like `foo` into a `string` index signature.
{
// Property is not a union with `undefined`, keep it as-is.
[Key in keyof T as DefinedKeyFilter<T, Key>]: T[Key];
} & {
// Property _is_ a union with defined value. Set as optional (via `?`) and remove `undefined` from the union.
[Key in keyof T as OptionalKeyFilter<T, Key>]?: Exclude<T[Key], undefined>;
}
>;
/**
Returns whether the given key of `ObjectType` has the `readonly` modifier.
The key belongs to the object, so no distribution or `any` handling is needed.
*/
export type IsReadonlyProperty<ObjectType, Key extends keyof ObjectType> =
(
// An index signature does not satisfy a required property, so this only matches a declared key. `Required` keeps optional declared keys, and `Record` treats `0` and `'0'` as the same property.
Required<ObjectType> extends Record<Key, unknown>
? Key
// A mapped type over a literal key copies only the modifier of a declared property, so map over the index signatures that cover the key instead. Like in TypeScript, a `number` index signature also covers numeric string keys, and a `string` index signature applies only when no other index signature covers the key. The mapped type visits each index signature on its own, while `keyof` would merge a template literal signature into `string`.
: keyof {[Property in keyof ObjectType as Key extends Property | (number extends Property ? `${number}` : never) ? (string extends Property ? never : Property) : never]: never} extends infer SpecificKey
? [SpecificKey] extends [never] ? string : SpecificKey
: never
) extends infer MappedKey extends keyof ObjectType
? IsEqual<
{[Property in MappedKey]: ObjectType[Property]},
{readonly [Property in MappedKey]: ObjectType[Property]}
>
: never;
/**
Normalize keys by including string and number representations wherever applicable.
@example
```ts
type A = NormalizedKeys<0 | '1'>;
//=> 0 | '0' | 1 | '1'
type B = NormalizedKeys<string>;
//=> string | number
type C = NormalizedKeys<number>;
//=> number | `${number}`
type D = NormalizedKeys<symbol | 'foo'>;
//=> symbol | 'foo'
```
*/
export type NormalizedKeys<Keys extends PropertyKey> =
| Keys
| (string extends Keys ? number : never)
| StringToNumber<Keys & string>
| KeyToString<Keys & number>;
/**
Get the given keys with their numeric and string aliases, including the runtime string spelling of enum keys.
@example
```ts
enum Color {
Red = 'red',
}
type A = KeyAliases<0 | Color.Red>;
//=> 0 | '0' | Color.Red | 'red'
```
*/
export type KeyAliases<Keys extends PropertyKey> = NormalizedKeys<Keys | KeyToString<Keys>>;
/**
Finds the keys of `BaseType` that the terminal paths name for deep setters, matching numeric, string, and enum spellings, and keeping a numeric key such as `1.2` distinct from a dotted string path such as `'1.2'`.
*/
export type DeepTerminalKeys<KeyPaths, BaseType> = KeyPaths extends `${string}.${string}`
? never
: KeyAliases<KeyPaths & PropertyKey> extends infer Keys
// An enum key and its literal spelling do not intersect, so declared keys are also matched by assignability. A key that an index signature covers is left to the intersection, because `number` is assignable to a numeric enum.
? (Keys & keyof BaseType) | Extract<keyof OmitIndexSignature<BaseType>, Exclude<Keys, keyof PickIndexSignature<BaseType>>>
: never;
/**
Finds the subpaths whose first property matches `Key` in `BaseType`. A declared property is selected on its own, without also changing its covering index signature.
*/
export type DeepSubPaths<KeyPaths, Key, BaseType> = KeyPaths extends `${infer Property}.${infer RestPath}`
// A noncanonical numeric segment, such as `01`, does not name a number key or an array index.
? Property extends KeyToString<(Key & string) | MatchingKey<Record<Key & number, unknown>, Property>>
? Property extends `${keyof OmitIndexSignature<BaseType> & (string | number)}`
? `${Key & (string | number)}` extends Property
? RestPath
: never
: RestPath
// A non-literal segment also selects each key assignable to its native template pattern.
: Extract<KeyToString<Key>, Property> extends never
? never
: RestPath
: never;
export {};