How to Make All Properties in a TypeScript Interface Optional?

In this article we will look at ways to make properties in an existing TypeScript interface optional. Let's assume we have the following interface:

interface MetaData {
    rating: number;
    views: number;
    tags: Array<string>;
}

Using Partial<T> Type

Depending on your use, you could simply declare the property type with Partial:

// TypeScript 2.1+
interface Product {
    // ...
    meta: Partial<MetaData>;
}

// example usage:
const product: Product = {
    meta: { }
};

Or, you could extend an interface using Partial like so:

// TypeScript 2.2+
interface ProductMetaData extends Partial<MetaData> {}

// example usage:
const metaData: ProductMetaData = {}

You could also use it with a type declaration:

type ProductMetaData = Partial<MetaData>;

// example usage:
const metaData: ProductMetaData = {}

Mapping Type Declarations as Optional

Similar to using Partial type, depending on your use, you could simply declare the type on the property inline like so:

// TypeScript 2.1+
interface Product {
    // ...
    meta: { [K in keyof MetaData]?: MetaData[K] };
}

// example usage:
const product: Product = {
    meta: { }
};

Or, you could extend a type like so:

// TypeScript 2.2+
type OptionalMetaData = {
    [K in keyof MetaData]?: MetaData[K];
}

interface ProductMetaData extends OptionalMetaData {}

// example usage:
const metaData: ProductMetaData = {}

Since, both keyof and the Partial type were introduced in TypeScript 2.1, it is recommended to use the latter instead. The reason being, the code above is exactly how the Partial type is defined in TypeScript:

type Partial<T> = {
    [P in keyof T]?: T[P];
};

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.