Skip to content

Typings: withComponent loses event handler callback types #1226

@esamattis

Description

@esamattis
  • emotion version: 10.0.7
  • react version: 16.8.1
  • typescript version: 3.3.1

Relevant code:

import styled from "@emotion/styled";
import React from "react";

const View = styled("div")({
    display: "flex",
    position: "relative",
    boxSizing: "border-box",
    flexDirection: "column",
});

const Input = styled(View.withComponent("input"))({
    color: "red",
});

function App() {
    return (
        <Input
            onChange={e => {
                // Implicit any on `e`
            }}
        />
    );
}

What you did:

Tried to extend styled component from div to input using withComponent

What happened:

Got Parameter 'e' implicitly has an 'any' type. type error with TypeScript strict mode.

image

Reproduction:

Just paste the example code to vscode.

Use this tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "esnext",
        "lib": ["es2018", "dom", "esnext"],
        "jsx": "react",
        "inlineSourceMap": true,
        "moduleResolution": "node",
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "noEmit": true,
        "esModuleInterop": true
    }
}

Problem description:

For some reason event handlers lose their types. The same thing happens with onClick, onBlur etc.

The event handler has following type

image

React.FormEvent<HTMLDivElement>) seems wrong.

If the withComponent does not change the underlying component type it works like expected

const View = styled("input")({
    display: "flex",
    position: "relative",
    boxSizing: "border-box",
    flexDirection: "column",
});

const Input = styled(View.withComponent("input"))({
    color: "red",
});

function App() {
    return (
        <Input
            onChange={e => {
                // `e` has correct React.ChangeEvent<HTMLInputElement> type!
            }}
        />
    );
}

Suggested solution:

🤷‍♂️

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions