1

Here is my typescript example using a colon:

interface props {
  legs: 2
};

interface body {
    head: string,
    torso: string,
    legs: number
};

const fnGetBodyUsingColon = (props: props): body => ({
  head: 'large',
  torso: 'larger',
  legs: props.legs
});

How can I show an example as above but using generics angle brackets?

This attempt gives me errors:

const fnGetBodyUsingAngleBrackets<T> = (props: T): T => ({
  head: 'large',
  torso: 'larger',
  legs: props.legs
});

fnGetBodyUsingAngleBrackets which lacks return type annotation, implicity has any return type

Steve Tomlin
  • 3,391
  • 3
  • 31
  • 63
  • 1
    I think you need to write `const fnGetBodyUsingAngleBrackets = (props: T): T => (…);` – Bergi Apr 29 '20 at 13:12

1 Answers1

1

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

jcalz
  • 264,269
  • 27
  • 359
  • 360
  • Thanks for your reply. I dont' necessarily want to use it. I'm just trying to create an example for myself to understand why I would need to use an angle bracket over just using colon. – Steve Tomlin Apr 29 '20 at 14:11