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' //}
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.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With