DEV Community

Davide Ficano
Davide Ficano

Posted on

Declare the type of a variable using that of a property

tiny how-tos to survive to the hostile code we write every day

Suppose you are using a type buried into a third-party library

type Line = {
  name: string;
  positions?: ReadonlyArray<number> | undefined;
}

const line: Line = {
  name: 'Line1',
  positions: [10, 20, 30]
};
Enter fullscreen mode Exit fullscreen mode

and you need to declare a variable with the same type used to define the property positions

You can create your own type and use it where necessary

type MyPositions = ReadonlyArray<number> | undefined
Enter fullscreen mode Exit fullscreen mode

on you can simply copy the definition

function showPositions(
  positions: ReadonlyArray<number> | undefined
): void {
  /// ...
}
Enter fullscreen mode Exit fullscreen mode

then call it with

showPositions(line.positions);
Enter fullscreen mode Exit fullscreen mode

but the library at some point changes the positions definition

type PositionName = 'top' | 'bottom';

type Line = {
  name: string;
  positions?: ReadonlyArray<number | PositionName> | undefined;
}

const line1: Line = {
  name: 'Line1',
  positions: [10, 'top', 30]
};
Enter fullscreen mode Exit fullscreen mode

and your code stops compiling

showPositions(line1.positions);

  Argument of type 'readonly (number | PositionName)[] | undefined' is not assignable to parameter of type 'readonly number[] | undefined'.
    Type 'readonly (number | PositionName)[]' is not assignable to type 'readonly number[]'.
      Type 'number | PositionName' is not assignable to type 'number'.
        Type 'string' is not assignable to type 'number
Enter fullscreen mode Exit fullscreen mode

using index access you can resolve this problem forever

Declare the variable type using directly the positions index in the type Line

function showPositions(
  positions: Line1['positions']
): void {
  /// ...
}
Enter fullscreen mode Exit fullscreen mode

and the code continues to compile

showPositions(line.positions);
showPositions(line1.positions);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)