简体   繁体   English

Typescript 函数参数作为函数或类型

[英]Typescript function parameter as function or type

I am working with a Typescript library authored by someone else.我正在使用由其他人创作的 Typescript 库。 In one of the functions, it takes a parameter that can be a function or a value like:在其中一个函数中,它接受一个可以是函数或值的参数,例如:

function returnDefault<T>(defaultVal: T | () => T): T {
    if(typeof defaultVal === 'function') {
        return defaultVal();
    }
    return defaultVal;
}

When attempting to use this function, I am getting a Typescript error "This expression is not callable. Not all constituents of type '(() => T) | (T & Function)' are callable. Type 'T & Function' has no call signatures."尝试使用此函数时,我收到 Typescript 错误“此表达式不可调用。并非所有类型为 '(() => T) | (T & Function)' 的成分都是可调用的。类型 'T & Function' 具有没有电话签名。” This error appears on the third line (return defaultVal();).此错误出现在第三行(返回 defaultVal();)。 What am I doing wrong here or how can I fix this error?我在这里做错了什么或者我该如何解决这个错误?

There is a few things you might need to change here.您可能需要在此处更改一些内容。

  • When defining a callback as a type, you need to enclose it in parenthesis.将回调定义为类型时,需要在括号中。
  • You might have to cast your variable as a function when calling it, and as a T when returning it.您可能需要在调用时将变量转换为函数,并在返回时将其转换为T
  • You might have to use the call method rather than parenthesis directly.您可能必须直接使用call方法而不是括号。

Here is working , untested example.这是有效的,未经测试的示例。

function returnDefault<T>(defaultVal: T | (() => T)): T {
    if(typeof defaultVal === "function") {
        return (defaultVal as Function).call({});
    }
    return defaultVal as T;
}

The syntax seams to be valid in the playground .语法接缝在操场上有效。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM