Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

typescript - 声明泛型类型的const(Declaring const of generic type)

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.

(然后,我想声明这种类型的const 。)

So, why typescript assumes that foo declaration is legit and bar is not?

(那么,为什么打字稿假定foo声明是合法的而bar不是?)

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?

(如果我不想显式重复FunctionType接口,是否有任何解决方法?)

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

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

//const bar: FunctionType<TValue> = (value) => { // Cannot find name 'TValue'
//}
  ask by idementia translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

(这意味着我们可以将其分配给具有指定泛型类型的const:)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...