首页 > 解决方案 > 管道函数参数类型被推断为任何

问题描述

基于我测试的高阶函数类型推断中的示例,TS 如何解析函数中的函数组合类型pipepipe

declare function pipe<A extends any[], B, C>(
    ab: (...args: A) => B, bc: (b: B) => C): (...args: A) => C;

这些是传递给管道的函数:

declare function list<T>(a: T): T[];
declare function box<V>(x: V): { value: V };
declare function numberBox(x: number[]): { value: number[] }

box具有泛型函数的 PR 示例正确地强制执行参数类型listBox(1)number

const listBox = pipe(list, box);  // T is retained
const x1 = listBox(1); // ... argument properly inferred to  number here

但是当我使用非泛型number[]框函数时,参数获取any类型:

const listNumberBox = pipe(list, numberBox)
const x21 = listNumberBox(1) // argument has any type
const x22 = listNumberBox("asdfasd") // this shouldn't be possible :/

我会假设具体类型的推断实际上比泛型类型(?)“更容易”,所以

1.) 为什么最后一个示例的参数类型推断为any

2.) 如何更改函数签名pipe以正确执行所有类型?

标签: typescriptfunctional-programmingtypescript-generics

解决方案


推荐阅读