Code Snippets
/

NonNullableKeys Utility Type

NonNullableKeys Utility Type

Filtering an object type to only the keys whose values are not nullable comes up everywhere: required-fields lists, mandatory column sets, GraphQL non-null fields. This snippet builds a `NonNullableKeys<T>` that returns just those keys, then layers in a `RequiredFields<T>` that produces a sub-object type, and a runtime helper that strips nullable fields from a value at runtime.

TypeScript
Medium
3 snippets
ts-utility-types
ts-mapped-types
ts-conditional-types
ts-generics

1,095 views

20

type NonNullableKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? never : null extends T[K] ? never : K }[keyof T];

interface User {
    id: string;
    nickname?: string;
    avatar: string | null;
    score: number;
}

type RequiredKey = NonNullableKeys<User>;

const keys = ['id', 'score'] as RequiredKey[];
console.log(keys.join(','));

The trick is the mapped-type-with-conditional pattern: build { [K in keyof T]: ... } where each value is K if the original type contains neither null nor undefined, and never otherwise. Indexing the result by [keyof T] collapses it into a union of just the surviving keys (the never entries are erased automatically). The -? removes optionality so an ?: field, which is implicitly T | undefined, is correctly classified as nullable. Use this whenever you need to derive a key list from an existing type rather than maintain it by hand.