Home > Software engineering >  Typescript Playground Error on using generic type with Arrow function
Typescript Playground Error on using generic type with Arrow function

Time:11-13

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?

CodePudding user response:

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

  • Related