Daniel Salvadori
Daniel Salvadori

Reputation: 435

How to access generic TypeScript type in function body?

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)?

Upvotes: 0

Views: 493

Answers (2)

jpthesolver2
jpthesolver2

Reputation: 1155

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

const func = <T extends number>(x: T) => x;

Upvotes: 2

Daniel Salvadori
Daniel Salvadori

Reputation: 435

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

Upvotes: 0

Related Questions