Having a tricky time with Typescript and finding the correct typing for my variable. What seems to be the issue?
The variable selected
in my code can either be of type DistanceSplit
or number
. I have an array that looks like this:
[-100, DistanceSplit, DistanceSplit, DistanceSplit, -100]
While everything works fine when selected
is of type any
, I am now aiming to remove all instances of any
from my code for better clarity. However, doing so leads to some compilation errors.
Specifically, errors like
Type 'number' is not assignable to type 'DistanceSplit'
or selected.name is not assigned to type number
start popping up.
I understand the reason behind these errors, but my question is: how do I go about resolving them in Typescript?
export const TRANSPONDER_Distance = -100;
export interface DistanceSplit {
ID: number;
name:string;
content:string
}
// working
public selected: any;
// not working
public selected: DistanceSplit | number;
function() {
this.selected.name = "bla"; // problem
}
Your assistance is much appreciated!