声明泛型类型的 const [英] Declaring const of generic type

查看:44
本文介绍了声明泛型类型的 const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Attempting to reduce boilerplate, I'm declaring some sort of generic function interface as a type. Then I want to declare a const of such type. So, why typescript assumes that foo declaration is legit and bar is not? Aren't these declarations practically identical? Is typescript lacking simple feature or am I missing some details? Is there any workarounds, if I do not want explicitly repeat FunctionType interface?

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

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

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

推荐答案

恰好是函数的泛型类型与作为泛型函数的类型之间存在差异.

There is a difference between a generic type that happens to be a function and a type that is a generic function.

你定义的是一个泛型类型,它是一个函数.这意味着我们可以将其分配给具有指定泛型类型的常量:

What you defined there is a generic type that is a function. This means that we can assign this to consts that have the generic types specified:

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

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

To define a type that is a generic function we need to put the type parameter before the arguments list

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

这篇关于声明泛型类型的 const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆