How to Pick Some Properties of a TypeScript Type and Make Them Required?

Learn how to construct a new type from an existing one with specific properties as required

The Required utility type in TypeScript does not allow selection of specific set of properties. Therefore, you can combine it with the Pick utility type to select some properties from an existing TypeScript type and make them required. It would have the following syntax:

// TypeScript 2.1+
type RequiredPick = Required<Pick<Type, Keys>>;

You would use it, for example, in the following way:

// TypeScript 2.1+
interface Foo {
    bar?: string;
    baz?: number;
    qux?: boolean;
}

type Example = Required<Pick<Foo, 'bar' | 'qux'>>;

This would select "bar" and "qux" from "Foo", and make them required in the new type.

You can also create a reusable "RequiredPick" utility type, like so:

// TypeScript 2.1+
type RequiredPick<T, K extends keyof T> = Required<Pick<T, K>>;

You would use it, for example, in the following way:

interface Foo {
    bar?: string;
    baz?: number;
    qux?: boolean;
}

type Example = RequiredPick<Foo, 'bar' | 'qux'>;

const ex: Example = { bar: 'xyz', qux: true };

If any of the required properties are missing, TypeScript would complain:

// Error: Property '...' is missing in type '...' but required in type '...'
const ex1: Example = { };
const ex2: Example = { bar: 'xyz' };
const ex3: Example = { qux: true };

Hope you found this post useful. It was published . Please show your love and support by sharing this post.