5

On using generic type with Arrow function, Typescript Playground throws error Cannot find name 'T'

Here is the link

function hasAllProperties <T>(obj: any, props: (keyof T)[]): obj is T {
    return props.every((prop) => obj.hasOwnProperty(prop))
}

// This throws error , wont compile 
const hasAllPropertiesArrow = <T>(obj: any, props: (keyof T)[]): obj is T => {
    return props.every((prop) => obj.hasOwnProperty(prop))
}

As I am new to generic types , I assume its not a bug with ts playground rather my lack of understanding. Also how can I rewrite the normal function as arrow function?

Solaris
  • 674
  • 7
  • 22
  • Please consult this https://stackoverflow.com/questions/56835492/error19-35-ts2304-cannot-find-name-t-why-i-cant-extend-interface-in-ts – Abdullah Khan Nov 12 '21 at 19:12
  • Disable jsx or add a trailing comma, see https://stackoverflow.com/q/41112313/ – iz_ Nov 12 '21 at 19:21

1 Answers1

6

This is a design limitation of the TypeScript parser; see microsoft/TypeScript#15713 for an authoritative answer. The syntax const x = <T>() fools the compiler into thinking that <T> is a JSX tag; you can verify this by looking at the rest of the error message, which says something like JSX element 'T' has no corresponding closing tag.

If you don't need JSX/TSX support you can remove the --jsx compiler option setting as in this Playground link. If you do need JSX support then you can work around this by using a trailing comma after the introduction of the T type parameter:

const hasAllPropertiesArrow = <T,>(obj: any, props: (keyof T)[]): obj is T => {
    return props.every((prop) => obj.hasOwnProperty(prop))
}

This comma has no effect on the meaning of the code but it stops the parser from getting confused.

Playground link to code

jcalz
  • 264,269
  • 27
  • 359
  • 360