变量声明的泛型类型

问题描述 投票:0回答:1

我有一个返回通用类型函数的高阶函数,如下所示:

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
typescript
1个回答
0
投票

您可以使用类型注释

<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
© www.soinside.com 2019 - 2024. All rights reserved.