TypeScript Interfaces & the generics Partial, Omit & Pick

·

2 min read

We use typescript to define what type of data each variable in our code will hold. This brings Javascript into line with most other languages. We can use interfaces to define the types within an object, and there are some extras we can use to extend these interfaces - Omit, Partial and Pick being three of them.

Lets look at an ordinary interface called Everything

interface Everything {

    a: number;

    b: string;

    c: Array<string>

}

Partial

Now let's say you wanted to use this interface, but only needed a couple of the properties, eg perhaps you only have a and b when you begin to use the object and then you will be adding c a bit further on in the class. This is where Partial comes in handy...

let everything:Partial<Everything> = {

    a: 1;

    b: "string"

}

Partial is a generic and looks like this;

type Partial<T> = {

    [P in keyof T]-?: T[P]

}

...it makes all properties in T optional

Another useful case where Partial can help...

interface MyInterface  {
    a: number;
    b: string;
}

let OriginalObject: MyInterface = {
    a: 6,
    b: "hello"
}
let update: Partial<MyInterface> = {a: 0}
let updatedObject = {...OriginalObject, ...update} //updatedObject  {a: 0, b: "hello"}
Object.assign(OriginalObject, update)//OriginalObject  {a: 0, b: "hello"}

The above allows you to be sure that the property will definitely be the correct type without having to write the update interface yourself. If for example you tried to update MyInterface so that 'a' becomes a string, your update logic would throw an error, because 0 is not a string.

Omit

You can also make a new interface cherry picking properties using Omit, like this;

interface AlmostEverything = Omit<Everything, 'a'>

is the same as saying

 interface AlmostEverything  {

    b:string;

    c: Array<string>;

}

Pick

similarly you can use Pick to select just one/a couple of property/ies

interface SpecificThing = Pick<Everything, 'a'>

is the same as saying

interface SpecificThing { a: number;}

All the wisdom in this article is thanks to Calvin Wylie who explained all this to me, any mistakes in this article though are entirely my own.