Skip to content

Object is "not comparable" when using JSX attributes on array entry #47211

Closed

Description

Bug Report

When I define a type or interface that extends React.HTMLAttributes<HTMLElement>, attempting to cast an array of objects to an array of that type fails if any of those objects has a data- attribute.

🔎 Search Terms

React, JSX, data attributes

🕗 Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about array type assertions.

⏯ Playground Link

Playground link with relevant code

💻 Code

import React from 'react';

interface MyProps extends React.HTMLAttributes<HTMLElement> {
  label: string;
}

// Works
const props = {
  label: 'abc',
  'data-testid': 'foo',
} as MyProps;

// Error: "Type '{ label: string; 'data-testid': string; }' is not comparable to type 'MyProps'."
const propsArray = [
  {
    label: 'abc',
    'data-testid': 'foo',
  },
] as MyProps[];

You can also replicate it more simply with this one-liner:

[{'data-testid': 'foo'}] as React.HTMLAttributes<HTMLElement>[];

🙁 Actual behavior

The array fails type checking with this error:

Conversion of type '{ label: string; 'data-testid': string; }[]' to type 'MyProps[]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Type '{ label: string; 'data-testid': string; }' is not comparable to type 'MyProps'.
    Object literal may only specify known properties, and ''data-testid'' does not exist in type 'MyProps'.(2352)

🙂 Expected behavior

No type error should occur here.

Activity

  1. dragomirtitian commented on Dec 22, 2021

    @dragomirtitian
    Contributor

    As mentions in #28960 you can model this interface in Typescript now (#28960 (comment)).

    You could use

    interface MyProps extends React.HTMLAttributes<HTMLElement> {
      [n: `data-${string}`]: any
      label: string;
    }

    Playground Link

    Any further changes are more likely to be required in the types for react (they could add the index signature to HTMLAttributes)

  2. typescript-bot commented on Jan 5, 2022

    @typescript-bot
    Contributor

    This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

  3. locked as resolved and limited conversation to collaborators on Oct 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions