typescriptjsx

In Typescript, why is JSX.IntrinsicElements not working as documentation describes?


I'm trying to use JSX on the server side, without React. I'm following the typescript docs about JSX here, and wrote the following in a .tsx file.

declare namespace JSX {
  interface IntrinsicElements {
    foo: any
  }
}
let elt1 = <foo/>
let elt2 = <bar/>

The linked docs say:

In the above example, <foo/> will work fine but <bar/> will result in an error ...

But for me, they both result in the same error:

Property 'foo' does not exist on type 'JSX.IntrinsicElements'.
Property 'bar' does not exist on type 'JSX.IntrinsicElements'.


Solution

  • You need module augmentation. I got the answer from here. Try this:

    import React from "react";
    
    declare module "react" {
      namespace JSX {
        interface IntrinsicElements {
          foo: any
        }
      }
    }
    
    let elt1 = <foo/>
    let elt2 = <bar/>
    

    Demo

    The reason your code doesn't work is because JSX.IntrinsicElements is taken from @types/react and redeclaring the namespace won't work. Also you'll notice your code will work if you don't import react (demo). Module augmentation basically extends the @types/react types.