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
[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
There seems to be a mismatch in the types of parameters between onChange and onActivityChange.
Try this
Generic type should have the type specified.
Update your last line to this and the error should be gone
Playground