Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript: Check if variable has been initialised

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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;

TS Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading