【问题标题】:What is the variable type if it takes a function?如果它需要一个函数,变量类型是什么?
【发布时间】:2017-10-06 12:01:49
【问题描述】:

我正在编写一个构造函数,它接受一个字符串、int 和一个函数(可能还有更多我目前不知道的东西)。到目前为止,我有以下内容。

export class Blobb {
  constructor(public value: number, 
              public name: string, 
              public mapping: function,
              public misc: any) { ... }
}

显然,变量 mapping 使编译崩溃,因为 function 不是有效类型。我不知道该怎么处理它。

传递给构造函数的函数是否有特定类型? any 是首选方法吗?我应该考虑声明自己的类型吗?

如果它有任何意义,则要传递的函数将始终是这样的(当然,计算方式不同)。

mapping() {
  this.value * 13 + ": " + this.name;
}

【问题讨论】:

标签: function typescript parameters variable-types


【解决方案1】:

您可以使用确切的函数签名来注释参数,而不是将其指定为Function。在您的情况下,它可以输入为() => void:

export class Blobb {
  constructor(public value: number, 
              public name: string, 
              public mapping: () => void,
              public misc: any) { ... }
}

TypeScript 函数类型:https://www.typescriptlang.org/docs/handbook/functions.html#function-types

【讨论】:

  • 是否等同于@kennethchau 上面设置大写“f”的建议?
  • 对于您的特定示例(无参数,无返回类型),它可能是相同的。但是如果你有参数或返回类型,你可以像上面一样定义它们(例如:mapping: (param: number) => number)。仅将其键入为 Function 是无法做到的。
  • 我喜欢这种方法:+1。事实上,我只是将我的通用Function 更改为(input: number)=>string,我喜欢它。我唯一注意到的是,从anynumber,我锁定了例如Date。有没有办法声明输入是日期或数字,但没有别的
  • 你可以使用union types:(input: number | Date) => string
【解决方案2】:

我自己没有使用它们,但从文档中,我看到类型别名是一个东西(在 TS 1.4 中引入);

例如:

type NameResolver = () => string;
function getName(n: NameOrResolver): Name {...}

Typescript Advanced Types

【讨论】:

  • True,类型别名是函数类型的首选语法形式,但如果需要重载,也可以使用带有() 成员的接口。
【解决方案3】:

你可以在es2015或更高版本中使用'Function'接口,所以它看起来像,

export class Blobb {
  constructor(public value: number, 
              public name: string, 
              public mapping: Function,
              public misc: any) { ... }
}

【讨论】:

    【解决方案4】:

    我认为您需要 Function 加上大写的“F”而不是 function

    function 是我相信声明一个新函数的关键词。

    【讨论】:

      猜你喜欢
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      • 2013-09-18
      • 1970-01-01
      • 2015-02-12
      相关资源
      最近更新 更多