Home > Enterprise >  Typescript specify interface or number type on parameter
Typescript specify interface or number type on parameter

Time:01-16

I have an interface for a parameter which can be either an object or a number.

I'm trying to write a method whereby a person can specify an object like {min: 0, max: 99} or they can specify a number which would be just a number.

eg: number(9) or number({min: 2, max:991})

I get this error:

Property 'max' does not exist on type 'number | NumberOptionsType'.

interface NumberOptionsType {
  max?: number;
  min?: number;
}

number(options?: NumberOptionsType | number): number {
    let possible: NumberOptionsType = {};
    if (!options) {
      // define a min and max
    }
    if (typeof options === 'object') {
      possible = options;
    }

    if (typeof options === 'number') {
      possible.max = 99999;
      possible.min = 0;
    }

    const max = (options && options.max) || 99999; //options.max raises the error
    const min = (options && options.min) || 0; //options.min raises the error

    const randomNumber = Math.floor(Math.random() * (max - min   1)   min);

    return randomNumber;
  }

CodePudding user response:

Just assert the type, ie:

 const max = (options && (options as NumberOptionsType).max) || 99999; //no longer throws error
 const min = (options && (options as NumberOptionsType).min) || 0; //no longer throws error

as a side note, since your code uses same values for when you pass in a number or when you pass in nothing, you code can be simplified like:

    interface NumberOptionsType {
      max?: number;
      min?: number;
    }

    function getNumber(options?: NumberOptionsType | number): number {
      const defaultMax = 99999;
      const defaultMin = 0;
      let max = (options as NumberOptionsType)?.max || defaultMax;
      let min = (options as NumberOptionsType)?.max || defaultMin;

      const randomNumber = Math.floor(Math.random() * (max - min   1)   min);

      return randomNumber;
    }

CodePudding user response:

Just check on type of options, as mentioned in the comments:

  function number(options?: NumberOptionsType | number): number {
      let possible: NumberOptionsType = {};
      if (!options) {
        // define a min and max
      }
      if (typeof options === 'object') {
        possible = options;
      }
  
      if (typeof options === 'number') {
        possible.max = 99999;
        possible.min = 0;
      }
  
      const max = typeof options === 'object'? options.max: 99999; //options.max raises the error
      const min = typeof options === 'object'? options.min: 0;; //options.min raises the error
  
      const randomNumber = Math.floor(Math.random() * (max - min   1)   min);
  
      return randomNumber;
    }
  •  Tags:  
  • Related