我有一个返回通用类型函数的高阶函数,如下所示:
function generator<B>() {
return (b: B) => b
}
// typeof getB = (b: unknown) => unknown
const getB = generator()
getB("hello") // this works
getB(1142) // this works
在这种情况下如何设置
getB
类型的泛型?例如,类似以下内容:
const getB<T> = generator<T>()
// typeof getNumber = (b: number) => number
const getNumber = getB<number>
getNumber("hello") // this errors
getNumber(1142) // this works
// typeof getString = (b: string) => string
const getString = getB<string>
getString("hello") // this works
getString(1142) // this errors
您可以使用类型注释
<B>(b: B) => B
:
function generator<B>() {
return (b: B) => b
}
const getB: <B>(b: B) => B = generator()
// typeof getNumber = (b: number) => number
const getNumber = getB<number>
getNumber("hello") // this errors
getNumber(1142) // this works
// typeof getString = (b: string) => string
const getString = getB<string>
getString("hello") // this works
getString(1142) // this errors