6

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?

2

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.