我想在高阶函数的内部函数中使用泛型作为参数。但是,当我这样做时,外部函数的参数会丢失它们的类型(变成 any
)。
这是我尝试做的一个例子。我希望在第 2 行出现错误。
type TestFunc = <T>(outerArg: string) => (innerArg: T) => number
const test: TestFunc = <T>(outerArg) => (innerArg: T) => innerArg ? outerArg * 3 : 0 // no error because `outerArg` is `any` (unexpected)
当 innerArg
不是泛型时,我会得到预期的错误:
type TestFunc = (outerArg: string) => (innerArg: boolean) => number
const test: TestFunc = (outerArg) => (innerArg: boolean) => innerArg ? outerArg * 3 : 0 // error because `outerArg` is `string` (expected)
问题
在第一个示例的第 2 行,outerArg
的类型为 any
。在第二个示例的第 2 行,outerArg
的类型为 string
。它们为什么不同?
更多详情
我的目标是允许在评估外部函数时指定 T
。例如:
type TestFunc = <T>(outerArg: string) => (innerArg: T) => number
const test: TestFunc = (outerArg) => (innerArg) => innerArg ? outerArg.length * 3 : 0
const test2: TestFunc = <T>(outerArg) => (innerArg: T) => innerArg ? outerArg * 3 : 0 // want error
const fourBool = test<boolean>('str')
console.log(fourBool(true))
console.log(fourBool(1)) // want error
const fourNum = test<number>('str')
console.log(fourNum(true)) // want error
console.log(fourNum(1))
最佳答案
你有两个功能:
1) 具有返回数字的泛型类型的函数,
2) 和一个接受数字并返回泛型的函数。
正如您在评论中提到的,您使用的是带有类型参数的箭头函数,但这对两个函数都不起作用。您可以将内部函数声明为泛型,并使用类型参数声明外部函数:
type InnerFunc<T> = (inner: T) => number;
type TestFunc = <T>(outer: number) => InnerFunc<T>;
const test: TestFunc = <T>(outerArg: number) => (innerArg: T) => innerArg ? outerArg * 3 : 0;
const fourBool = test<boolean>(4);
fourBool(true); // OK
fourBool(1); // error
关于typescript - 高阶函数中的通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45441328/