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]
};
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
on you can simply copy the definition
function showPositions(
positions: ReadonlyArray<number> | undefined
): void {
/// ...
}
then call it with
showPositions(line.positions);
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]
};
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
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 {
/// ...
}
and the code continues to compile
showPositions(line.positions);
showPositions(line1.positions);
Top comments (0)