How to override type properties in TypeScript

A simple one off solution as of TypeScript 3.5 could be:

type HexColorLine = Omit<Line, 'color'> & {
  color: number;
}

This is not supported at the moment. TypeScript would need a concept of subtraction types. Proposals exist https://github.com/Microsoft/TypeScript/issues/12215 and https://github.com/Microsoft/TypeScript/issues/4183

Fix

Create a base type :

type LineBase = {
  start: Point;
  end: Point;
}
type LineBase = LineBase & {
  color: string; //'cyan'/'aquablue'/...
}

TL;DR:

type Omit<T, K> = Pick<T, Exclude<keyof T, K>>
type Override<T, U> = Omit<T, keyof U> & U

type ColorNumber =  {
  color: number;
}

type HexColorPoint = Override<
  Line,
  ColorNumber
> // --> {start: Point; end: Point; color: number}

I assume you wanted to do

type HexColorLine = Line & {
  color: number;
}

instead of

type HexColorLine = Point /* <-- typo? */ & {
  color: number;
}

With Typescript >2.8 i was able to override like this:

From https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html :

We did not include the Omit type because it is trivially written as Pick<T, Exclude<keyof T, K>>.

// So we define Omit -.-
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>

// Sidenote: 
// keyof is just getting all the keys for a given type separeted by |
// keyof Line --> 'start' | 'end' | 'color'

// And we define Override which unions the type without unwanted keys and the 
// type defining the new keys
type Override<T, U> = Omit<T, keyof U> & U

// just define which properties you want to redefine 
// and remove "Point &" as it will be done in the Override type
type HexColorLine =  {
  color: number;
}
type HexColorPoint = Override<
  Line,
  HexColorLine
> // --> {start: Point; end: Point; color: number}

Create a helper type:

type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;

Usage:

type HexColorLine = Overwrite<Line, { color: number }>

Tags:

Typescript