As I transition from JavaScript to TypeScript, I have encountered a situation with filtering null
values from an array. In JavaScript, I would typically use .filter(x => x)
to achieve this. However, in TypeScript, it is asking me to specify that the array may contain null
, even though the intention is to remove all instances of null
from the array:
interface ILabels {
alias: string
publicKey: string
lat: number
long: number
}
const labels: ILabels[] = data.map((d) => {
if (d.lat && d.long) {
return {
alias: d.alias || d.publicKey,
publicKey: d.publicKey,
lat: d.lat,
long: d.long,
};
}
return null;
}).filter((x) => x);
I am wondering how I can communicate to TypeScript that there will not be any null
values in this array. The error message thrown by TypeScript reads as follows:
TS2322: Type '({ alias: string; publicKey: string; lat: number; long: number; } | null)[]' is not assignable to type 'ILabels[]'. Type '{ alias: string; publicKey: string; lat: number; long: number; } | null' is not assignable to type 'ILabels'. Type 'null' is not assignable to type 'ILabels'.