3

How to write this typescript function with generic arguments in a variable function(store the function in a variable)?

function identity<T>(arg: T): T {
  return arg;
}

I tried this and it complains Cannot find name 'React'

const identity = <T>(arg: T): T => {
    return arg;
}
1
  • What specifically do you mean by "doesn't work"? Commented Feb 21, 2021 at 22:40

1 Answer 1

4

Assuming you're referring to the Cannot find name 'React'. error, that's because typescript tries to parse <T>.. as a React element. You can add a comma after the generic parameter to prevent this: <T> ~> <T,>

const identity = <T,>(arg: T): T => {
  return arg;
}

TypeScript playground

Alternatively, you can add a dummy extends clause, e.g. <T extends {}>, but <T,> is the cleanest solution.

Sign up to request clarification or add additional context in comments.

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.