skip to Main Content

Initial simplified question

Can’t assign onActivityChange type to onChange:

type ActivityType = { 
  id: string; 
  name: string;
}

const onChange = <TOption extends {}>(value: TOption) => {
  console.log(value);
}

const onActivityChange = (value: ActivityType) => {
  console.log(value);
}

// error
const handler: typeof onChange = onActivityChange;

Error:

Type '(value: ActivityType) => void' is not assignable to type '<TOption extends {}>(value: TOption) => void'.
  Types of parameters 'value' and 'value' are incompatible.
    Type 'TOption' is not assignable to type 'ActivityType'.
      Type '{}' is missing the following properties from type 'ActivityType': id, name

ts playground

[edited] My usecase, react

I’m using react:

import * as React from "react";
import { render } from "react-dom";

type ActivityType = {
    id: string;
    name: string;
}

type DropdownProps = {
    onChange: <TOption extends {}>(value: TOption) => void;
};

const Dropdown: FC<DropdownProps> = ({ onChange }) => <div onClick={onChange}>Hello, World!</div>;

const App = () => {
    const onActivityChange = (value: ActivityType) => {
      console.log(value);
    };
    
    // error
    return <Dropdown onChange={onActivityChange} />;
};

render(<App />, document.getElementById("root"));

Error:

Type  (value: ActivityType) => void  is not assignable to type  <TOption extends {}>(value: TOption) => void 
Types of parameters  value  and  value  are incompatible.
Type  TOption  is not assignable to type  ActivityType 
Type  {}  is missing the following properties from type  ActivityType :  id, name 

How to fix it and save type inference of onChange type?

2

Answers


  1. There seems to be a mismatch in the types of parameters between onChange and onActivityChange.
    Try this

        type ActivityType = { 
      id: string; 
      name: string;
    }
    
    const onChange = <TOption extends {}>(value: TOption) => {
      console.log(value);
    }
    
    const onActivityChange = (value: ActivityType) => {
      console.log(value);
    }
    
    const handler: <TOption extends {}>(value: TOption) => void = onActivityChange;
    
    Login or Signup to reply.
  2. Generic type should have the type specified.

    Update your last line to this and the error should be gone

    const handler: typeof onChange<ActivityType> = onActivityChange; 
    

    Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search