Answer to the syntax question:
The generic type parameter is part of the call signature, not part of the variable you assign it to. The syntax looks like this, with <T>
moved after the =
:
const identity = <T>(t: T): T => t;
update: if the above does not compile, it is because you are using .tsx files or JSX support and that confuses the parser. See this Q/A for more information. To work around that, you can use a trailing comma after the type parameter declaration, like
const identity = <T,>(t: T): T => t;
Please note that your example code is problematic. The compiler rightfully gives an error if you fix the syntax:
const fnGetBodyUsingAngleBrackets = <T>(props: T): T => ({
head: 'large',
torso: 'larger',
legs: props.legs
}); // error!
// Type '{ head: string; torso: string; legs: any; }' is not assignable to type 'T'.
That's because you are claiming that fnGetBodyUsingAngleBrackets()
takes an argument of any type T
and returns a value of the same type as the argument. The value you're returning is almost certainly not of the same type as the argument:
const oops = fnGetBodyUsingAngleBrackets({ foo: "bar", baz: "qux" });
// const oops: { foo: string; baz: string; }
console.log(oops.foo.toUpperCase()); // no compiler warning; error at runtime
I'm not sure why exactly you want to use generics in this example so I'm not sure how to advise on how you should proceed here.
Okay, hope that helps; good luck!
Playground link to code