简体   繁体   English

Typescript 在参数上指定接口或编号类型

[英]Typescript specify interface or number type on parameter

I have an interface for a parameter which can be either an object or a number.我有一个参数接口,它可以是 object 或数字。

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.我正在尝试编写一种方法,一个人可以指定一个 object 像 {min: 0, max: 99} 或者他们可以指定一个数字,这只是一个数字。

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

I get this error:我收到此错误:

Property 'max' does not exist on type 'number |类型 'number | 上不存在属性 'max' 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;
  }

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;
    }

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;
    }

In order to handle such kind of cases, you usually need split your function into several smaller.为了处理这种情况,您通常需要将您的 function 分成几个更小的。 See this example:看这个例子:

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

const toRequired = ({ min, max }: NumberOptionsType): Required<NumberOptionsType> => ({
  min: min || 0,
  max: max || 99999
})

const getDefault = (): Required<NumberOptionsType> => ({ min: 0, max: 99999 })

const handleObject = (obj: Required<NumberOptionsType>) => {
  const { max, min } = obj

  return Math.floor(Math.random() * (max - min + 1) + min)
}

const number = (options?: NumberOptionsType | number) => {

  if (typeof options === 'object') {
    return handleObject(toRequired(options))
  }

  return handleObject(getDefault())
}

Playground操场

I don't understand why you have provided possible variable, this is why I have removed it.我不明白你为什么提供了possible变量,这就是我删除它的原因。 As far as I understood, if options is undefined you should apply default values.据我了解,如果undefined options ,则应应用默认值。 The same way you treat regular number , this is why I check only for typeof options === 'object' .与您对待常规number的方式相同,这就是为什么我只检查typeof options === 'object'原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Typescript 中指定参数类型的值 - Specify values of a parameter type in Typescript typescript接口:指定完整的特定枚举作为参数 - typescript interface: specify full specific enum as parameter 如何在TypeScript中为对象元素指定接口类型? - How to specify an interface type to an object element in TypeScript? 如何在Typescript中将类定义指定为参数类型 - How specify class definition as parameter type in Typescript 如何指定Typescript函数参数数组类型 - How to specify a Typescript function parameter array type 带有类型或接口的 TypeScript 解构默认参数 - TypeScript destructured default parameter with type or interface TypeScript:'编号| undefined' 不可分配给“number”类型的参数 - TypeScript: 'number | undefined' is not assignable to parameter of type 'number' 在打字稿中,如何根据其属性而不是接口指定类型? - In typescript, how can I specify a type based on its properties, not an interface? 如何在打字稿中的接口中指定回调,而不必为其命名类型 - How do I specify a callback in an interface in typescript but not have to name a type for it TypeScript : &#39;string | 类型的参数 number&#39; 不能分配给类型为 &#39;number&#39; 的参数 - TypeScript : Argument of type 'string | number' is not assignable to parameter of type 'number'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM