Write Generic Type syntax for arrow function
/ 2 min read
Genaric Type syntax for Arrow function
using a function which gives random item from a list but it was written inside a method; so extract the method and make it generic so that if I pass number[] and return will be number
[!NOTE] writing error list on hover is in commented code inside code snippet
and using it later
ths gives type error
Trial 1: added return type ( not working )
and later
still same error but now changed typing near to the method name as below
this gives another error along with previous errors
Trial 2: added return type ahead of function ( not working )
changed location of typing while function call
Trial 3: Added ahead of function name ( not working )
but interestingly, this time error on below code has been gone
Added type ahead to parenthesis of fat arrow in angle bracket ( working )
and later
and this works without any type error.
More refactor
- adding
is un-necessary while function calling, as we passed argument already typed as string []
- remove explicit
string[]
ahead tothemes
as it isstring[]
already. - Remove typing after
)
in function definition.
so we can remove the typing and call it like this
and if you hover on the method name it will show the correct tying instead of T
as below
Final Typed version
function definition
function invocation
Key points
- avoid explicit typing
- use
just before opening parenthesis in arrow function approach