Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript Playground Error on using generic type with Arrow function

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading