首页 > 解决方案 > 声明泛型类型的 const

问题描述

为了减少样板文件,我将某种通用函数接口声明为一种类型。然后我想声明一个const这样的类型。那么,为什么打字稿假定foo声明是合法的而bar不是合法的呢?这些声明实际上不是相同的吗?打字稿缺少简单的功能还是我缺少一些细节?如果我不想明确重复FunctionType界面,是否有任何解决方法?

type FunctionType<TValue> = (value: TValue) => void;

const foo = <TValue>(value: TValue): void => {
}

//const bar: FunctionType<TValue> = (value) => { // Cannot find name 'TValue'
//}

标签: typescripttypes

解决方案


恰好是函数的泛型类型和泛型函数的类型之间存在差异。

您在那里定义的是一个泛型类型,它是一个函数。这意味着我们可以将其分配给具有指定泛型类型的 const:

type FunctionType<TValue> = (value: TValue) => void;
const bar: FunctionType<number> = (value) => { // value is number
}

要定义一个泛型函数类型,我们需要将类型参数放在参数列表之前

type FunctionType = <TValue>(value: TValue) => void;
const bar: FunctionType = <TValue>(value) => { // generic function
}

推荐阅读