简体   繁体   English

TypeScript:函数的两个参数类型

[英]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 doSomethinghref 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.

相关问题 Function 参数在 typescript 中有两种可能的类型 - Function argument with two possible types in typescript TypeScript - function 参数类型相等 - TypeScript - function argument types equality 带部分类型注释的TypeScript函数参数解构 - TypeScript function argument destructuring with partial types annotation 将类型分配给 Typescript 中的通用映射 function 的参数 - Assign types to argument of generic mapping function in Typescript 是否可以将 function 参数类型包装在 TypeScript 中? - Is it possible to wrap function argument types in TypeScript? 函数类型是否优先于打字稿中的参数类型? - Do function types take precedence over argument types in typescript? Typescript 匹配 function 类型和参数类型的 map - Typescript match between map of function types and argument types 如何将具有多种类型的参数作为参数传递给 Typescript 中的函数? - How to pass an argument with multiple types as an argument to a function in Typescript? 如何在TypeScript中为函数参数设置参数名称和类型? - How do I set argument names and types for a function argument in TypeScript? 打字稿:当函数可以是多种函数类型时,函数参数出错 - Typescript: Error on function argument when the function can be of multiple function types
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM