KeysOfType type
Lists the keys of the properties whose type matches: the numeric fields of a record to chart, the boolean flags of a settings object.
ts
import type { KeysOfType } from 'utils';Signature
ts
export type KeysOfType<T, V> = { [K in keyof T]-?: T[K] extends V ? K : never }[keyof T];
/**
* Keeps the properties whose type matches.
*
* @template T - The object type.
* @template V - The property type to keep.
* @example
* type Flags = PickByType<Settings, boolean>;
*/
export type PickByType<T, V> = Pick<T, KeysOfType<T, V>>;Parameters
| Name | Description |
|---|---|
T | The object type. |
V | The property type to look for. |
Example
ts
type NumericField = KeysOfType<Sample, number>; // 'speed' | 'heading'Tests
Line coverage: 0 %.
- ✅ keeps the matching properties
- ✅ lists the keys of matching properties
Source
src/types/pick-by-type.ts (on GitHub)
Source code
ts
/**
* Lists the keys of the properties whose type matches: the numeric fields of a record to chart, the
* boolean flags of a settings object.
*
* @template T - The object type.
* @template V - The property type to look for.
* @example
* type NumericField = KeysOfType<Sample, number>; // 'speed' | 'heading'
*/
export type KeysOfType<T, V> = { [K in keyof T]-?: T[K] extends V ? K : never }[keyof T];
/**
* Keeps the properties whose type matches.
*
* @template T - The object type.
* @template V - The property type to keep.
* @example
* type Flags = PickByType<Settings, boolean>;
*/
export type PickByType<T, V> = Pick<T, KeysOfType<T, V>>;Test file
ts
import type { KeysOfType, PickByType } from './pick-by-type';
describe('PickByType', () => {
it('keeps the matching properties', () => {
expectTypeOf<PickByType<{ a: string; b: number; c: string }, string>>().toEqualTypeOf<{ a: string; c: string }>();
});
});
describe('KeysOfType', () => {
it('lists the keys of matching properties', () => {
interface Sample {
name: string;
speed: number;
heading: number;
isValid?: boolean;
}
expectTypeOf<KeysOfType<Sample, number>>().toEqualTypeOf<'heading' | 'speed'>();
expectTypeOf<KeysOfType<Sample, boolean | undefined>>().toEqualTypeOf<'isValid'>();
});
});Keywords: keys, of, type, types