78

Let's say I have an interface:

interface IUser {
  email: string;
  id: number;
  phone: string;
};

Then I have a function that expects a subset (or complete match) of that type. Maybe it will pass an entire object, maybe it will just pass in {email: "[email protected]"}. I want the type checker to allow for both.

Example:

function updateUser(user: IUser) {
  // Update a "subset" of user attributes:
  $http.put("/users/update", user);
}

Does Typescript support this sort of behavior yet? I could find it very useful, particularly with paradigms like Redux.

To clarify, the goal is:

  1. Avoid re-writing an interface and manually setting all attributes to optional.
  2. Avoid assignment of unexpected attributes (such as spelling mistakes).
  3. Avoid imperative logic such as if statements, which forfeit benefits of compile time type checking.

UPDATE: Typescript has announced support for mapped types which should solve this problem once published.

2
  • 2
    isn't Partial what you're looking for?
    – user1267177
    Jun 23, 2017 at 6:52
  • They did not exist when I asked the question. I added a link later, after they were added to TS.
    – Rick
    Jun 23, 2017 at 14:45

7 Answers 7

123

It's worth noting that Partial<T>, as suggested in the accepted answer, makes all fields optional, which is not necessarily what you need.

If you want to make some fields required (e.g. id and email), you need to combine it with Pick:

type UserWithOptionalPhone = Pick<IUser, 'id' | 'email'> & Partial<IUser>

Some explanation:

What Pick does is that it lets you specify a subset of the interface succinctly (without creating a whole new interface repeating the field types, as suggested by other answers), and then lets you use those, and only those fields.

function hello1(user: Pick<IUser, 'id' | 'email'>) {
}

hello1({email: '@', id: 1}); //OK

hello1({email: '@'}); //Not OK, id missing

hello1({email: '@', id: 1, phone: '123'}); //Not OK, phone not allowed

Now, this is not exactly what we need, as we want to allow, but not require phone. To do that, we "merge" the partial and the "picked" version of our type by creating an intersection type, which then will have id and email as required fields, and everything else as optional – exactly how we wanted it.

function hello2(user: Pick<IUser, 'id' | 'email'> & Partial<IUser>) {
}

hello2({email: '@', id: 1}); //OK

hello2({email: '@', id: 1, phone: '123'}); //OK

hello2({email: '@'}); //Not OK, id missing
87

Typescript now supports partial types.

The correct way to create a partial type is:

type PartialUser = Partial<IUser>;
3
  • Is there a way to specify a specific, partial subset of a class? i.e. a class where id and email are mandatory but phone just doesn't exist?
    – James
    May 22, 2019 at 13:41
  • 2
    @James please have a look at my solution down below. this is what you are asking for. Jul 12, 2019 at 12:35
  • 7
    @James The Pick type is what you need. Use Pick<IUser, 'id' | 'email'> if you don't want to allow phone at all, and Pick<IUser, 'id' | 'email'> & Partial<IUser> if you want to allow phone, but not require it (while requiring id and email). See my answer for details. Jul 17, 2019 at 7:07
27

What you want is this

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

this makes sure, that U is a subset of T and returns U as a new type. for example:

interface Foo {
 name: string;
 age: number;
}

type Bar = Subset<Foo, {
 name: string;
}>;

you can not add new properties to Bar which are not part of Foo - and you can not alter types in a non-compatible way. this also works recursively on nested objects.

1
  • 1
    Yo this is pretty cool, I didn't know you could forward-reference in type assignment like this but I guess it makes sense. Slick stuff.
    – dudewad
    Jul 7, 2020 at 22:05
6

proper solution with mapped types:

updateUser<K extends keyof IUser>(userData: {[P in K]: IUser[P]}) {
    ...
}
1
  • 1
    Partial is way easier. But your answer cleared my some of the doubts about what's the syntax in this kind of scenario. Thanks! Jan 4, 2019 at 20:12
2

You can declare some or all fields as optional fields.

interface IUser {
  email: string; // not optional
  id?: number; // optional 
  phone?: string; // optional
};
4
  • 1
    This is close, but not quite what I want. In the case of IUser, all fields are mandatory. It's just under certain circumstances that I would want it to be a partial match.
    – Rick
    Apr 26, 2016 at 17:01
  • the requirements are contradictory, you can't have a field be optional and mandatory at the same time. :P I guess you could use 2 interfaces to get that though..
    – toskv
    Apr 26, 2016 at 17:02
  • 1
    There are many times when you would want this and other languages (like Flow) allow for it. It is for the sake of DRYness that you would want to allow a subset under certain circumstances. Consider Backbone model updates, where you have named parameters that must be a subset of the model's attributes.
    – Rick
    Apr 26, 2016 at 17:06
  • 1
    I agree with @toskv. If under certain situations those fields may be absent, then those are not mandatory. You can define different interfaces for those different scenarios. In any case I'm not sure why someone downvoted his answer, it is correct. Apr 26, 2016 at 17:14
0

You can seperate it into different interfaces:

interface IUser {
    id: number;
};

interface IUserEmail extends IUser {
    email: string;
}

interface IUserPhone extends IUser {
    phone: string;
}

Have your method receive the base IUser interface and then check for the fields you need:

function doit(user: IUser) {
    if (user.email) {

    } else if (user.phone) {

    }
}
1
  • This implements supertypes, not subtypes. Jun 16 at 23:44
-4

If I understand this question correctly, you want something like Flow's $Shape

So, in one place, you may have something that requires the type

interface IUser {
  email: string;
  id: number;
  phone: string;
};

Then, in another place you want a the type with the same type as IUser just with all the fields now optional.

interface IUserOptional {
  email?: string;
  id?: number;
  phone?: string;
};

You want a way to auto-generate IUserOptional based on IUser without having to write out the types again.

Now, I don't think this is possible in Typescript. Things may change in 2.0, but I don't think we're even close to something like this in Typescript yet.

You could look at a pre-compiler which would generate such code for you before typescript runs, but that doesn't sound like a trivial thing to do.

With this problem in mind, I can only suggest you try Flow instead. In flow you can just do $Shape<IUser> to generate the type you want programmatically. Of course, Flow differs from Typescript in many big and small ways, so keep that in mind. Flow is not a compiler, so you won't get things like Enums and class implementing interfactes

1
  • 1
    This defeats purpose of creating interfaces - they should be re-usable and composable. This one assumes maintining two versions of the same entity just for the sake of required fields. Apr 28, 2020 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.