Conditional and union types are better

Elsewhere I advocate for that developers use http response objects. TypeScript has a couple nifty improvements that can really make these response objects simple: Union and Conditional types.

Let’s say you have an Author object returned from your API. Now you want to add response properties. Type Union to the rescue!

export interface Response {
  success: boolean;
  message?: string;
}

export interface Author {
  id: number;
  name: string;
  age: number;
}

// the union is an ampersand
type AuthorResponse = Author & Response;

// and a typed example
const x = <AuthorResponse>{
  success: true,
  name: 'Alex',
  age: 34
};

That worked great for your /artist GET request, but now you need an /artist PUT. But you just need to edit the age and leave the name null. And now for Mapped Types.

// this works more like a type builder func than a type
type MyPartialTypeForEdit<Type> = {
  [Property in keyof Type]?: Type[Property];
} & { id: number };

type AuthorEdit = MyPartialTypeForEdit<Author>;

// and a typed example
const y = <AuthorEdit>{
  id: 1,
  age: 35,
}