Rick Rick - 1 year ago 95
TypeScript Question

Does Typescript support "subset types"?

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, made it will just pass in
{email: "t@g.com"}
. I want the type checker to allow for both.


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
    statements, which forfeit benefits of compile time type checking.

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download