[英]TypeScript: two argument types for function
I need pass to function doSomething
string or result of function, that returns string: 我需要传递给函数
doSomething
字符串或函数的结果,返回字符串:
const someFunction = (href: string) => {
...
};
type a = () => string;
export function doSomething (href: string | a): void {
someFunction(href);
}
But I get an error: 但是我收到一个错误:
Argument of type 'string | 类型'字符串|的参数 a' is not assignable to parameter of type 'string'.
a'不能赋值为'string'类型的参数。 Type 'a' is not assignable to type 'string'.
类型'a'不能分配给'string'类型。
Function of type a
returns string, then why I get this error? 函数类型
a
返回字符串,那么为什么我得到这个错误?
Thanks in advance. 提前致谢。
doSomething
's href
if of type string | () => string
doSomething
的href
if类型string | () => string
string | () => string
, whereas someFunction
accepts only a string
. string | () => string
,而someFunction
只接受一个string
。
If TypeScript had allowed this, there would have been a possibility for you to pass a () => string
into a function that can only deal with string
s, which would have resulted in runtime errors. 如果TypeScript允许这样做,那么你有可能将一个
() => string
传递给一个只能处理string
s的函数,这会导致运行时错误。
It may be the case that doSomething
needs to work with string-returning functions, but you can't expect someFunction
to be able to, especially after you specifically defined the parameter it accepts to only be of type string
. 可能是
doSomething
需要使用字符串返回函数,但你不能指望someFunction
能够,特别是在你明确定义它接受的参数只是string
类型之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.