使用 foo
作为属性引发错误:
// App.tsx
// 👇 throws
const App = () => <div foo></div>
export default App
Type '{ foo: true; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.
Property 'foo' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.ts(2322)
但是使用 foo-foo
很好,这是为什么呢?// App.tsx
// 👇 no error is thrown
const App = () => <div foo-foo></div>
export default App
最重要的是,如何在 TypeScript 中定义这样的类型?即只允许标准或 kebab-case 属性。
最佳答案
答案在 JSX section of the Typescript Handbook :
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.
JSX 的整个部分是一本非常有启发性的读物。
恐怕“如何在 TypeScript 中定义这样的类型”问题的答案是......我们没有。 JSX 支持内置在编译器中。然而,我们可以定制很多有趣的东西。
关于javascript - 为什么允许使用 kebab-case 非标准属性,而不允许使用其他属性?以及如何在 TypeScript 中定义这样的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67673754/