TypeScript: Make Type Properties Optional

This is especially useful when testing, when we only want to provide one or two of all the properties:

interface Person {
    name: string;
    age: number;
    location: string;

The following two achieve the same effect:

type PartialPerson = Partial<Person>;

interface PartialPerson {
    name?: string;
    age?: number;
    location?: string;

So we can either do a type cast with as, or better yet, use Partial:

const Tom = { name: "Tom" } as Person;
const Jerry: Partial<Person> = { name: "Jerry" };

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.