How do I get the TypeScript engine to allow custom HTML attributes in JSX?

后端 未结 2 1470
盖世英雄少女心
盖世英雄少女心 2021-01-12 20:42

I presume the TypeScript engine within Visual Studio Code has received an update that is now complaining for the first time that my pre-existing custom props on HTML element

相关标签:
2条回答
  • 2021-01-12 21:18

    Note: If an attribute name is not a valid JS identifier (like a data-* attribute), it is not considered to be an error if it is not found in the element attributes type.

    <div data-custom="bar" />

    https://www.typescriptlang.org/docs/handbook/jsx.html#attribute-type-checking https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*

    0 讨论(0)
  • 2021-01-12 21:24

    React type definition file (by default - index.d.ts when staring with create-react-app) contain list of all the standard HTML elements, as well as known attributes.

    In order to allow custom HTML attributes, you need to define it's typing. Do that by expanding HTMLAttributes interface:

    declare module 'react' {
      interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
        // extends React's HTMLAttributes
        custom?: string;
      }
    }
    
    0 讨论(0)
提交回复
热议问题