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

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

To pick a specific set of properties from an existing TypeScript type, and make them optional, you can do any of the following:

Combining Partial and Pick Utility Types

Since the Partial utility type in TypeScript does not allow selection of specific set of properties, you can simply combine it with the Pick utility type, which would have the following syntax:

// TypeScript 2.1+
type PartialPick = Partial<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 = Partial<Pick<Foo, 'bar' | 'qux'>>;

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

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

// TypeScript 2.1+
type PartialPick<T, K extends keyof T> = Partial<Pick<T, K>>;

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

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

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

Either way you choose, the following cases would be valid:

const ex1: Example = { bar: 'xyz', qux: true };
const ex2: Example = { bar: 'xyz' };
const ex3: Example = { qux: true };
const ex4: Example = { };

For properties that don't exist on the type, this would throw an error:

// Error: Object literal may only specify known properties...
const ex5: Example = { invalid: 'not-allowed' };
const ex6: Example = { baz: 123 };

Creating a Custom Utility Type

You can create a custom, reusable, "PartialPick" utility type, like so:

type PartialPick<T, K extends keyof T> = {
    [P in K]?: T[K];
};

This would allow you to pick a few properties from an existing type and make them optional. You can use it in the following way:

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

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

const ex1: Example = { bar: 'xyz', qux: true };
const ex2: Example = { bar: 'xyz' };
const ex3: Example = { qux: true };
const ex4: Example = { };

For properties that don't exist on the type, this would throw an error:

// Error: Object literal may only specify known properties...
const ex5: Example = { invalid: 'not-allowed' };
const ex6: Example = { baz: 123 };

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