typescript - Typescript中两个函数的联合类型

标签 typescript types

我有一种情况,我有一个类型,它是两个函数的联合,这两个函数的一个参数的类型是文字值。归结为一个最小的例子,它本质上是这样的:

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() 本质上是一个重载函数,它接受两者 minifull,因此应该是交集类型,而不是并集。

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)

PlayGround

根据经验,当您声明一个接受两种类型 A B args 的函数时,该函数应该是& -打字。

关于typescript - Typescript中两个函数的联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43662729/

相关文章:

list - Scala groupby 元素类型

python - Pandas 0.8 read_csv 无法识别 'dtype' 参数

typescript - Vue + TypeScript + CSS 模块

generics - 在 Typescript 中创建通用方法装饰器

c - 数据类型检查导致 C 中永无止境的循环

java - 如何设置列表的引用类型?

c++ - 数据类型和结构

javascript - 使用箭头函数 react this.setState 导致控制台出错

javascript - 如何通过 Angular 中的截面操作来改变这种 body 操作?

typescript - 为什么 Typescript 会推断由没有未定义的缺失键检索到的值的类型?