Repository navigation
Mimicking JSX attributes behaviour with object types #28960
Description
Activity
- Reacted by Oliver Joseph Ash, tydira, St John Peaster, Olivier Tassinari, Mario Jerkovic, Laurin, patrik and Javier Falcon
- addedSuggestionAn idea for TypeScriptAn idea for TypeScriptIn DiscussionNot yet reached consensusNot yet reached consensus
on Dec 11, 2018 - added a commit that references this issue
on May 4, 2021 eps1lon commented
on Aug 23, 2021 ContributorMore actionsIt seems like this can be solved in TypeScript 4.4 with template literal types as object keys:
import * as React from 'react'; type DataAttributeKey = `data-${string}`; interface HTMLAttributes extends React.HTMLAttributes<any> { [dataAttribute: DataAttributeKey]: any; } function Component(props: { host: HTMLAttributes }) { return <div {...props.host} /> } <Component host={{ 'data-testid': 'component', 'role': 'generic', // @ts-expect-error shouldError: 1 }} />
Reacted by Titian Cernicova-Dragomir, Michał Pietraszko, Jordan Paisley, David Johnston, Jimmy Wilson, Damien Golding, Mateusz Gawliński, Olivier Tassinari, ako-v, Chris Duff and 2 moreReacted by silverwindReacted by jared laser, Michał Pietraszko, Mateusz Gawliński, Kyle Poole and Amit BeckensteinReacted by Oliver Joseph Ash, Josh Wooding, Pablo Saucedo, Tobias Waltl and Jayden SericPossibly related: #47211
in vue3 typescript I am having some property does not exist in the HtmlElement error. please help me to solve this issue.
(property) dataButtons: string
(property) data-buttons: string
Type '{ class: string; dataButtons: string; "data-buttons": string; }' is not assignable to type 'HTMLAttributes'.
Property 'dataButtons' does not exist on type 'HTMLAttributes'.ts(2322)
Reacted by Chris, Michał Lutecki and MartinOliverJAsh commented
on Feb 13, 2023 ContributorAuthorMore actionsTogether with module augmentation it can be defined once in a global type definitions module, e.g.
src/types/react.d.ts:import 'react'; declare module 'react' { export interface HTMLAttributes<T> { [dataAttribute: `data-${string}`]: any; } }
Not sure why this isn't supported in
@types/reactalreadyReacted by silverwindReacted by karine-devsightseps1lon commented
on Sep 5, 2024 ContributorMore actionsNobody proposed the change yet. It may not be trivial to do since adding properties may break existing typechecking. Somebody just needs to own this change.
Search Terms
jsx object invalid data attribute nested component react
Suggestion
We have this behaviour for JSX:
https://www.typescriptlang.org/docs/handbook/jsx.html#attribute-type-checking
I want this same behaviour but for object types. This is necessary for times when we want to pass some props as a nested object (for whatever reason). Currently this errors:
As far as I'm aware, there's currently no way to extend the above props type to allow for this behaviour.
Checklist
My suggestion meets these guidelines: