我有以下功能;
const capitalize = (input) =>
(!(typeof input === 'undefined'))
? input
.split(' ')
.map(capitalizeWord)
.join(' ')
: undefined
这要么接受一个字符串并返回一个字符串,要么接受一个 undefined 并返回 undefined,但绝不会接受一个字符串并返回 undefined 或接受 undefined 并返回一个字符串。我的想法是类型应该类似于 (void => void) & (string => string)
但这根本不是我想要的; Flow 担心我没有指定要大写输入是字符串还是未定义,而我希望它做的是有效地分派(dispatch)到正确的类型。当我让流只推断类型时,它推断出 (void | string) => (string | void)
,这太宽泛了。正确的签名是什么?
最佳答案
你可以定义generic作为 string
或 void
:
const capitalize = <T: string | void>(input: T): T =>
(!(typeof input === 'undefined')) ? input
.split(' ')
.join(' ')
: input
但是,它应该返回传递的 arg,而不是 undefined
。 Try .
关于javascript - 接受字符串并返回字符串或接受 void 并返回 void 的函数的类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53541043/