1

Imagine we have two types, that are similar, though not the same:

type First<G> = (arg: G) => G
type Second = <G>(arg: G) => G

Now obviously when talking about these two types, there are differences, I am wondering, if someone can explain, in detail, what those differences are, how do we refer to them, they are both "generics" but do they have a better, more distinct name, so that I can search for this, because I couldn't find anything.

From what I gather - First type requires us to specify a generic when defining a variable of said type whereas the Second type infers it from usage, depending on the line of code where we used it. Are there any other benefits? Or negatives? One particular issue I am having with the Second form is the fact that I cannot assert to G

I've also ran into an issue of following:


const myFunction: Second = (arg) => {
  let someValue = getExternalValue() // typeof someValue === unknown
  return someValue as G // this is an issue, I cannot access G
}

Now I know assertions are bad, and all that, but is there a way of writing this to access this generic G ? Obviously the example is not a real codebase code, just demonstrating a point.

Dellirium
  • 1,362
  • 16
  • 30
  • 1
    Does this answer first your question? [TypeScript how to create a generic type alias for a generic function?](https://stackoverflow.com/questions/62720954/typescript-how-to-create-a-generic-type-alias-for-a-generic-function) – Elias Schablowski Feb 21 '23 at 22:30
  • The difference between `First` and `Second` is that `First` is a generic type that goes to a function and `Second` is a generic function. To access `G` in your example, add `` in front of the `(arg)` [What is the syntax for Typescript arrow functions with generics?](https://stackoverflow.com/questions/32308370/what-is-the-syntax-for-typescript-arrow-functions-with-generics) – Elias Schablowski Feb 21 '23 at 22:35

0 Answers0