0

Using a generic type on a TypeScript function:

const func: <T extends number>() => void = () => {
   const x: T = 1
}

Emits the following error:

Cannot find name 'T'.  TS2304

    69 | const func: <T extends number>() => void = () => {
  > 70 |    const x: T = 1
       |             ^
    71 | }

How can I use generic types inside a function (and not just on its signature)?

Daniel Salvadori
  • 427
  • 6
  • 15
  • 1
    The syntax is `const func = () => { const x: T = 1 }`. You'll get another error, but this is already another question – Aleksey L. Jul 05 '20 at 17:08

2 Answers2

2

If you want to type arrow functions, try using the implied typing method from this answer.

const func = <T extends number>(x: T) => x;
jpthesolver2
  • 1,107
  • 1
  • 12
  • 22
0

Using the alternative function notation makes that error disappear:

function func<T extends number>(): void {
   const x: T = 1
}

And we instead get the following error, which makes sense:

Type '1' is not assignable to type 'T'.
  '1' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'number'.  TS2322

    69 | export function func<T extends number>(): void {
  > 70 |    const x: T = 1
       |          ^
    71 | }
Daniel Salvadori
  • 427
  • 6
  • 15