Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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' //} 
like image 404
idementia Avatar asked Jul 05 '18 18:07

idementia


People also ask

How do you define a generic type in TypeScript?

Assigning Generic ParametersBy passing in the type with the <number> code, you are explicitly letting TypeScript know that you want the generic type parameter T of the identity function to be of type number . This will enforce the number type as the argument and the return value.

How do I restrict a generic type in Java?

Java For Testers Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.

How do generics work in TypeScript?

The TypeScript documentation explains Generics as “being able to create a component that can work over a variety of types rather than a single one.” Great! That gives us a basic idea. We are going to use Generics to create some kind of reusable component that can work for a variety of types.


1 Answers

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 } 
like image 79
Titian Cernicova-Dragomir Avatar answered Nov 01 '22 10:11

Titian Cernicova-Dragomir