Typescript: Mimicking JSX attributes behaviour with object types

Created on 11 Dec 2018  路  1Comment  路  Source: microsoft/TypeScript

Search Terms

jsx object invalid data attribute nested component react

Suggestion

We have this behaviour for 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

import React, { FC } from 'react';

const MyComponent: FC<{ myProp: string }> = props => null;
<MyComponent myProp="foo" data-test="foo" />;

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:

const MyComponent2: FC<{ props: { myProp: string } }> = props => null;
<MyComponent2 props={{ myProp: 'foo', 'data-test': 'foo' }} />;

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:

  • [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [x] This feature would agree with the rest of TypeScript's Design Goals.
In Discussion Suggestion feature-request

Most helpful comment

You want a combination of #6579 (#21044) and #26797. Today, the logic is hardcoded into how we check jsx literals, but with those you could define, eg, type Props<P> = P & {[index: /^data-/]: unknown}

>All comments

You want a combination of #6579 (#21044) and #26797. Today, the logic is hardcoded into how we check jsx literals, but with those you could define, eg, type Props<P> = P & {[index: /^data-/]: unknown}

Was this page helpful?
0 / 5 - 0 ratings