我有一种情况,我有一个类型,它是两个函数的联合,这两个函数的一个参数的类型是文字值。归结为一个最小的例子,它本质上是这样的:
type FetchMini = (id: number, representation: 'mini') => MiniUser;
type FetchFull = (id: number, representation: 'full') => FullUser;
function f(fetchUser: FetchMini | FetchFull) {
fetchUser(2, 'mini');
fetchUser(2, 'full');
}
这两个调用都使编译器失败并显示消息:
Cannot invoke an expression whose type lacks a call signature. Type 'FetchMini | FetchFull' has no compatible call signatures.`
我认为我了解发生这种情况的原因,(...我认为)但我能做些什么呢?
这是一个类似的问题,但没有得到答案:Union of functions is not callable even with parameters that meet each function's constraints
最佳答案
您的 fetchUser()
本质上是一个重载函数,它接受两者 mini
和 full
,因此应该是交集类型,而不是并集。
type MiniUser = { name: string }
type FullUser = { firstName: string, lastName: string, age: number }
type FetchMini = (id: number, representation: 'mini') => MiniUser;
type FetchFull = (id: number, representation: 'full') => FullUser;
type FetchBoth = FetchMini&FetchFull
function f(fetchUser: FetchBoth) {
fetchUser(2, 'mini');
fetchUser(2, 'full');
}
function fetchBoth(id: number, representation: 'mini'): MiniUser
function fetchBoth(id: number, representation: 'full'): FullUser
function fetchBoth(id: number, representation: 'mini' | 'full') {
if (representation==='mini')
return { name: 'Mini' }
if (representation==='full')
return { firstName: 'Full', lastName: 'User', age: 20 }
}
f(fetchBoth)
根据经验,当您声明一个接受两种类型 A 和 B args 的函数时,该函数应该是& -打字。
关于typescript - Typescript中两个函数的联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43662729/