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.
CodePudding user response:
The reason you get the used before assigned
error is because Typescript doesn't know that undefined
is a possible value/type for label
or even the other value
.
Your first codeblock actually works if you just simply specify the type as:
let label: string | undefined;
let value: number | undefined;
CodePudding user response:
I would just declare it as possibly being undefined
, because it is:
let label: string | undefined;
let value: number | undefined;
CodePudding user response:
You can also use the '!' (Definite Assignment Assertion).
Example:
let label!: string;
let value!: number;
Example: TS Playground