Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[react] React wrapped components do not offer any way to customise the type of events dispatched #2129

@WickyNilliams

Description

@WickyNilliams

Description

createComponent from @lit-labs/react does not offer any way to customise the type of events being dispatched. As can be seen in the following lines, Event is always used:

type Events<S> = {
[P in keyof S]?: (e: Event) => unknown;
};

Steps to Reproduce

Consider some code in a lit component like:

this.dispatchEvent(
  new CustomEvent<string>('some-event', {
    detail: "foobar",
    bubbles: true,
    composed: true,
  })
);

And a react wrapper like:

export const MyComponent = createComponent(React, "my-component", MyLitComponent, {
  onSomeEvent: "some-event",
});

TS generates a type like this from the react wrapper:

onSomeEvent: ((e: Event) => unknown) | undefined;

Event is incompatible with CustomEvent<string> in type terms, so I cannot re-type at the call site like this without an error:

{/* does not work! */}
<MyComponent
  onSomeEvent={(e: CustomEvent<string>) => console.log(e.detail)}
/>

It would be nice if createComponent supported some form of generics for defining event types, since I can likely auto-generate this from my custom elements manifest (at least to some extent: seems the event type there is only CustomEvent and not CustomEvent<string>)

Live Reproduction Link

N/A

Expected Results

TS should know that e here is CustomEvent<string>, without needing to explicitly state the type:

<MyComponent
  onSomeEvent={(e) => console.log(e.detail)}
/>

Actual Results

I have been forced to do this, which is a shame, as we lose all type safety:

<MyComponent
  onSomeEvent={(e: any) => console.log("who needs types, anyway?!", e.detail)}
/>

Browsers Affected

N/A

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

Status

✅ Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions