idementia
idementia

Reputation: 941

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'
//}

Upvotes: 67

Views: 65975

Answers (2)

Hyster
Hyster

Reputation: 726

I have been trying to solve the same problem, which occurs especially when I'm using higher order functions (or React components) returning other generic functions (or components). I've found following solution:

interface GenericFunctionType {
    <T>(x: T): string
}

const genericFunction: GenericFunctionType = (x) => `doSomething with X ${x}`

Upvotes: 30

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250366

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
}

Upvotes: 82

Related Questions