If I were to declare a type as a separate variable, such as:
type Foo = <T>(x: T) => T
Then use it to define a function:
const foo:Foo = x => {
let a = /*...*/
/*...function execution...*/
return a
}
How can I reference generic type T in the function body, such as to declare variable a:T ?
You cannot refer to this type argument in any way, because it's in type declaration. It's basically saying "You see, any function that is of type Foo is generic, you can pass a type argument to any function of this type, and its return type and arguments will depend on this type argument". This type argument T that you specify in Foo doesn't actually exist in any way, it's just there to signal to any caller of Foo that it can accept one.
Now you use this argument when you write the actual implementation of a function of type Foo. Like
type Foo = <T>(x: T) => T
const foo: Foo = <T>(x: T) => {
let a: T = x
return a
}
Or for example you could name it differently
type Foo = <T>(x: T) => T
const foo: Foo = <U>(x: U) => {
let a: U = x
return a
}
The Foo type doesn't enforce anything, it just says "this function has 1 type argument" and the function can call and use this argument however it wants. It's even free to ignore it completely
type Foo = <T>(x: T) => T
const foo: Foo = () => {
return 5 as any
}
Again, as far as the caller of the function is concerned, foo accepts one type argument just because foo is an implementation of the Foo type, even if foo doesn't actually use it.
Or you could add an extra type argument that is optional and an optional variable of this type
type Foo = <T>(x: T) => T
const foo: Foo = <U, K = number>(x: U, y?: K) => {
if(y) console.log(y)
let a: U = x
return a
}
And this is still valid, because whoever calls foo can look at the type definition and see "Ok, Foo accepts 1 type argument and 1 normal argument". If they now provide 1 type argument and 1 normal argument, it will still work because foo is fine working in such conditions.
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