TypeScript: Creating subset types from existing interfaces

Typescript allows us to create subsets of existing interfaces.

Let’s take an example:

You have a function that return IUser


IUser has many fields among them name and lastName.

Now let’s say that that functions allows you to specify the return properties (and in our case we just want to get the lastName)

We don’t want our IDE to suggest us that we can access the name or any other property.


For that reason we must do the following:


// Create an extension . In my case I added it to ts-extensions.ts

export type Subset<T extends U, U> = U;

// Then I create my interface as follows

type CustomUser = Subset<User.IUser,{ lastName: string; }>;
let result:CustomUser = await User.findById(2908, ['CLI_NAME']); //<-- This will return IUser only lastName will be defined

result.lastName // Our IDE will only autosuggest lastName. All other properties will be omitted. 




Leave a Reply

Close Menu