函数类型 #

创建一个类型化的函数,该函数会检查参数的类型,并能将它们与提供的多个签名进行匹配。类型化的函数会自动转换输入以找到匹配的签名。如果输入参数错误,类型化的函数会抛出信息丰富的错误。

请参阅 typed-function 库以获取详细文档。

Syntax #

math.typed(name, signatures) : function
math.typed(signatures) : function

Parameters #

Parameter Type Description
name string 为类型化函数设置可选名称
signatures Object<string, function> 包含一个或多个函数签名的对象

Returns #

Type Description
function 创建的类型化函数。

Throws #

Type | Description —- | ———–

Examples #

// create a typed function with multiple types per argument (type union)
const fn2 = typed({
  'number | boolean': function (b) {
    return 'b is a number or boolean'
  },
  'string, number | boolean': function (a, b) {
    return 'a is a string, b is a number or boolean'
  }
})

// create a typed function with an any type argument
const log = typed({
  'string, any': function (event, data) {
    console.log('event: ' + event + ', data: ' + JSON.stringify(data))
  }
})
Fork me on GitHub