302 文字
2 分

一部の属性値(data- など)は、型定義がJSXに含まれていなくても型エラーにならない

JSX を扱っていると型を定義していないのに、data 属性や aria 属性などを指定出来ることに気づくかもしれません。

<SomeComponent data-index={1} aria-current="page" />

これは TypeScript の仕様です。camelCase でない識別子は、JSX に存在しなくてもエラーになりません。

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. - https://www.typescriptlang.org/docs/handbook/jsx.html#attribute-type-checking

エラーになるケース#

  1. 存在しない camelCase の識別子はエラーになります。
// Error: Property 'someAttribute' does not exist
<SomeComponent someAttribute />
  1. DOM 本来の属性値をまとめたい場合や、子要素に属性値を与えたい場合に、オブジェクトを経由して data 属性などを渡そうとすると JSX の属性値として扱われないためエラーになります。
// Error: Object literal may only specify known properties, and '"some-attribute"' does not exist
<SomeComponent childProps={{ "some-attribute": "not-error" }} />

回避案としては明示的に型を指定したり、アサーションなどを使って黙らせる他、例えば data 属性をサポートしたければ次のようにするとお手軽です。

interface SomeComponentProps {
childProps: {
[dataAttribute: `data-${string}`]: any;
};
}
一部の属性値(data- など)は、型定義がJSXに含まれていなくても型エラーにならない
https://blog.ohirunewani.com/posts/some-attribute-do-not-cause-type-errors-even-if-type-definition-is-not-included-in-jsx/
作者
hrdtbs
公開日
2024-01-23
ライセンス
CC BY-NC-SA 4.0