I have some function as follows:
const myFunction = (columns: any, data: any) => {
let label: string;
let value: number;
//some section where it assigns label and value
for (let index = 0; index < columns.length; index++) {
const column: string = columns[index].fieldName;
const datapoint: string = data[index].formattedValue;
if (column.includes("KeyPointLabel")) {
label = datapoint;
}
if (column.includes("KeyPointValue")) {
value = Number(datapoint);
}
}
//if the above section worked as expected, they should have a value.
//so if it doesn't, throw an error.
if (typeof label === undefined) throw new Error() <--- ERROR HERE!!
return {label, value}
}
I want to null check for label and value. I have looked at a couple of other threads where it suggested to do if (typeof label === undefined) or if (label == null), etc. but any statement that references label or value gives me 'used before assigned' error.
The section where it assigns label and value is just a for-loop which looks through the columns to see if it has a column name that contains KeyPointLabel, assigns label = data[same index as column], and similarly for value. The form of columns and data is not something I can control.
Technically, I could do
let label: string = "";
let value: number = -1;
...
if(label === "" || value < 0) throw new Error();
return { label, value }
because my value is never expected to have a negative number and label never to be an empty string, but I was wondering if there is a bit more elegant solution.
//some section where it assigns label and value? Sounds like it'd make the most sense by far to throw in there when the conditional assignment fails, instead of afterwards