Home > Mobile >  How to change number or boolean type to just number type for returned value?
How to change number or boolean type to just number type for returned value?

Time:09-17

I created this simple function that returns 2 values - isNumber and convertedValue. I expect isNumber to be boolean type and convertedValue to be number type, but when I extract those values, I get number | boolean type for both values. How can I make changes so when I extract them that I get boolean type for isNumber and number type for convertedValue ?

    const numberValidator = (val: string, fn: (str: string) => number) => {
      const convertedValue = fn(val);
      const isNumber =
        typeof convertedValue === 'number' && isFinite(convertedValue);
      return [isNumber, convertedValue];
    };

        const [isNumber, convertedValue] = numberValidator(
          val,
          Number
        ); // now type for both values are "number | boolean"

CodePudding user response:

To get the correct return type, you can use as const behind the tuple.

const numberValidator = (val: string, fn: (str: string) => number) => {
  const convertedValue = fn(val);
  const isNumber =
    typeof convertedValue === "number" && isFinite(convertedValue);
  return [isNumber, convertedValue] as const;
};

const [isNumber, convertedValue] = numberValidator("abc", Number);

isNumber
// ^? const isNumber: boolean

convertedValue
// ^? const convertedValue: number

Otherwise, TypeScript will widen it to an array type (number | boolean)[]. But you want the tuple type [boolean, number].


Playground

CodePudding user response:

You could simply do as follow:

const numberValidator = (val: string, fn: (str: string) => number) => {
  const convertedValue = fn(val);
  const isNumber =
    typeof convertedValue === "number" && isFinite(convertedValue);
  return {isNumber, convertedValue};
};

const {isNumber, convertedValue} = numberValidator("1", Number);

  • Related