type-fest
Version:
A collection of essential TypeScript types
53 lines (39 loc) • 1.93 kB
TypeScript
import type {KeyToString} from './internal/string.d.ts';
import type {PropertyValue} from './property-value.d.ts'; // For `@link`
/**
Resolve a property key to the matching key type in an object, converting between numeric and string forms when needed.
Useful when composing generic property access utilities that accept either `0` or `'0'` for the same property. Returns `never` if no key matches.
Keys assignable to `keyof ObjectType` are returned unchanged, including keys covered by index signatures. Otherwise, numeric keys are tried as strings, and numeric strings as numbers only if converting back preserves their spelling. For example, `'01'` does not match `1`.
Distributes over a union of keys. For a union of objects, only keys in `keyof ObjectType` are considered, so a key must be common to all members. Plain strings do not select string enum keys. Array and tuple indices are not bounds-checked.
@example
```
import type {MatchingKey} from 'type-fest';
type StatusMessages = {
200: 'OK';
'404': 'Not found';
};
type SuccessKey = MatchingKey<StatusMessages, '200'>;
//=> 200
type NotFoundKey = MatchingKey<StatusMessages, 404>;
//=> '404'
type PickByKey<ObjectType extends object, Key extends PropertyKey> = Pick<ObjectType, MatchingKey<ObjectType, Key>>;
type Success = PickByKey<StatusMessages, '200'>;
//=> {200: 'OK'}
```
@see {@link PropertyValue} to get the value of the matching property.
@category Object
*/
export type MatchingKey<ObjectType extends object, Key extends PropertyKey> =
Key extends keyof ObjectType
? Key
: KeyToString<Key> extends keyof ObjectType
? KeyToString<Key>
: Key extends `${infer NumberKey extends number}`
// A numeric-looking string names a number key only when its spelling survives the conversion.
? `${NumberKey}` extends Key
? NumberKey extends keyof ObjectType
? NumberKey
: never
: never
: never;
export {};