typescript - 声明泛型类型的 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'
//}
解决方案
恰好是函数的泛型类型和泛型函数的类型之间存在差异。
您在那里定义的是一个泛型类型,它是一个函数。这意味着我们可以将其分配给具有指定泛型类型的 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
}
推荐阅读
- c++ - 提取整个字符串的序列(Arduino、C++、indexOf、子字符串)
- node.js - 无法在生产 heroku 应用上发送 API 请求
- xml - Azure DevOps 服务器: - 向工作项类型添加字段
- javascript - tensorflow js如何从另一个模型加载权重
- python - 有没有办法用定量值对 Python seaborn pairplot 中的点进行着色?
- python-3.x - 递归调用导致非类型返回
- php - 将 Laravel 集合转换为数组,括号前后不带引号
- c - 为什么这个结构需要比 sizeof 本身更多的分配空间?
- python - 如何在 SQLAlchemy for Flask 中创建具有自动递增主键的关联表?
- javascript - Javascript 异步函数不需要返回 Promise