Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override type properties in TypeScript

Tags:

typescript

For example, I have

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

But now I want to create new line type on the base of Line, so that it stores color as number:

type HexColorLine = Point & {
  color: number;
}

Now I expect the HexColorPoint type be equal to

{
  start: Point;
  end: Point;
  color: number;
}

But it equals to

{
  start: Point;
  end: Point;
  color: string | number;
}

Is there a way to override but not extend the prop type with some short syntax? Do i really have to define entirely new type for this?

like image 962
Eugene Beliaev Avatar asked Mar 28 '17 21:03

Eugene Beliaev


People also ask

Can we override function type in TypeScript?

To override a class method in TypeScript, extend from the parent class and define a method with the same name. Note that the types of the parameters and the return type of the method have to be compatible with the parent's implementation. Copied! class Parent { doMath(a: number, b: number): number { console.

How do you change TypeScript type?

The process of changing types is what is called “type casting”. Typecasting in strongly typed languages like C# allow us to convert types. string numStr = "123"; int numNum; bool isParsable = Int32. TryParse(numStr, out numNum);

What is the difference between interface and type in TypeScript?

The typescript type supports only the data types and not the use of an object. The typescript interface supports the use of the object.


1 Answers

Create a helper type:

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

Usage:

type HexColorLine = Overwrite<Line, { color: number }>
like image 161
Karol Majewski Avatar answered Sep 18 '22 06:09

Karol Majewski