Type annotate arguments for subset of a given type in TypeScript

Amit Merchant · August 31, 2020 ·

Often, there comes a scenario when you want to type annotate (or type hint) some of the variables or arguments for a subset of a given type.

For instance, let’s say, we have the following interface…

interface User {
    id: number;
    name: string;
    email: string;
}

And we want to type annotate one of the arguments of the following function using User, we can do it like so.

function updateDetail(user: User) {
    return {...user}
}

But let’s say, you want to add another argument which will be a subset of User type which only includes property email, how would do it? Well, there are utility types in TypeScript that come to rescue in such situations.

The Partial<Type> utility type

So, if we want to type annotate using the subset of User we can use Partial<User> as a type annotation, which will type check for any subset of User. So, if we want to add another argument in the previous function, we can do it like so.

function updateDetail(user: User, details: Partial<User>) {
    // logic to update user detail

    return {...user, ...details}
}

And this is how we can call it.

const user = {
    id: 1,
    name: 'Harry Potter',
    email: '[email protected]'
}

const details = {
    email: '[email protected]'
}

const updateUser = updateDetail(user, details);

Notice, the detail object is the subset of user, so this won’t throw any type error as long as detail is the subset of user. But as soon as, detail is not a subset of user, let’s say,

const details = {
    username: '[email protected]'
}

…it will throw the following error.

Type '{ username: string; }' has no properties 
in common with type 'Partial<User>'

Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!