0

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.

2
  • What is //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 Commented May 10, 2022 at 0:15
  • @CertainPerformance edited my question to add more details. Commented May 10, 2022 at 0:19

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

I would just declare it as possibly being undefined, because it is:

  let label: string | undefined;
  let value: number | undefined;

Comments

0

You can also use the '!' (Definite Assignment Assertion).

Example:

let label!: string;
let value!: number;

Example: TS Playground

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.