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

1
  • 1
    The syntax is const func = <T extends number>() => { const x: T = 1 }. You'll get another error, but this is already another question 🙂 Commented Jul 5, 2020 at 17:08

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.