Skip to content

KeysOfType

Extracts the keys of T whose values extend V.

Optional properties are matched by their non-nullable value type, so an optional string property still counts as a string key.

Available since v3.0.0

import type { KeysOfType } from '@helpers4/type';
type KeysOfType<T, V> = {
  [K in keyof T]-?: NonNullable<T[K]> extends V ? K : never;
}[keyof T]
type User = { id: number; name: string; email: string; active: boolean };
type StringKeys = KeysOfType<User, string>; // 'name' | 'email'
type NumberKeys = KeysOfType<User, number>; // 'id'

View source on GitHub