score:32
Concerning Function
and best practices
Function
in practice has unsufficient type-safety, being the super-type of all functions. You better replace it with a function type - see the "Solutions" section down under.
In above example, Function
is not assignable to the more narrow onClick
function type, which causes the error at hand (Playground example).
In addition to mentioned issue, here is what TypeScript docs say about Function
:
This is an untyped function call and is generally best avoided because of the unsafe any return type. If need to accept an arbitrary function but don’t intend to call it, the type
() => void
is generally safer.
typescript-eslint has discarded Function
with the ban-types
rule, emitting following message with default configuration (see also here):
The
Function
type accepts any function-like value. It provides no type safety when calling the function, which can be a common source of bugs. If you are expecting the function to accept certain arguments, you should explicitly define the function shape.
Better solutions
React already comes with built-in event handler-types to handle common events.
For exampleclick
(Playground):
type Props = {
onClick: React.MouseEventHandler<HTMLButtonElement>
};
const Submit = ({ onClick }: Props) => <button onClick={onClick}> click </button>
A more general alternative is to use function types as follows:
type Props = {
onClick: (event: React.MouseEvent<HTMLElement>) => void
};
void
is more restrictive than any
. There is no chance to return a value in the callback by accident, which would be possible with any
.
In summary, we embrace typing capabilities of TypeScript instead of using Function
or any
.
The parameter now is known to be MouseEvent
and the return type void
, identifying it as a callback.
Related
score:3
You can simply write it like this, which prevents any and is more telling. Especially for custom functions:
Interface Props { onClick: (e: Event) => void; }
This will tell the calling component, what onClick will expect and what the parameters are.
Hope this helps. Happy coding.
Source: stackoverflow.com
Related Query
- React prop types with TypeScript - how to have a function type?
- How to test with jest and typescript with types a basic react function component
- How do I fix a React TypeScript error with the return value of useHotkeys hook not matching the type of the div element ref prop
- How to prop drill with type interfaces in my React Typescript counter?
- Passing a function as a prop with different parameter types in React with Typescript
- How to use jest.spyOn with React function component using Typescript
- How do you correctly use React.lazy() in Typescript to import a react component with a generic type parameter?
- Is it possible to type a React function component with TypeScript without using arrow functions?
- Typescript React stateless function with generic parameter/return types
- How to type a Typescript React Component that accepts a Context with a super-set of properties
- How do I define a TypeScript type for React props where prop B is only accepted if prop A is passed to a component?
- How to use radium in React typescript (Error: has no properties in common with type 'CSSProperties'. TS2559)?
- Typescript type issue in map function of mixed types react
- How to type async function passed as prop to React component
- How to handle typescript function overloading with React Props
- How to type any param with React Typescript in Functional Component
- how to set prop type in react + typescript
- How to define an interface for React function component with defaultProps without throwing missing type error?
- How do you extract a specific TypeScript prop type from a React component?
- When passing a React functional Component as a parameter of a function, how should I declare the function parameter type with TS
- Typescript and React with complex prop type interface
- TypeScript errors in React Class Component property does not exist on type 'Readonly<{}>', not sure how to set types for state
- React function component prop default with TypeScript
- How to store values of a function type (e.g. arrow functions) with the React Hook useState?
- How to properly use TypeScript types with a Styled Component canvas on React
- How do you extract prop types from a React Component with defaultProps?
- Typescript types of composition Ramda lens with React useState set function
- How to define TypeScript types when used with React useState and the previous state inside a state updating function?
- How to create React Context that passes a function with Typescript
- React & Typescript: Omitting a prop with spread syntax results in typescript error. Advanced types
More Query from same tag
- Victory Chart issues with spacing between axis and tickValues
- How to remove subfolder name from Next Js URL?
- How to provide and consume context in the same component?
- react-sortable-tree - How to get the search API working
- select checkboxes and show up row - React js
- Received true for a non-boolean attribute test React Test Jest with data-testid
- ReactJS confusing 'JS code as text' and real JS code: Add javascript code as text in ReactJS div
- Ternary in jsx to add selected attribute to option
- URL routing issue when using react
- 404 error while sending data from React to Node?
- Webpack / babel-loader producing many errors in new project
- Where to define CSS files in React-Bootstrap?
- Make checkbox field mandatory using React
- Check if user is logged in or not using firebase in react
- React Uncaught TypeError: this.setState is not a function
- React/Redux: get the user geolocation using a promise and dispatch the position to the action creator
- How can I convert Redux toolkit reducers In react
- Check if a div element can receive paste event i.e if it is focused
- Tailwind custom background-image not working in production
- How to load image in asynchronous manner on hover effect in React.js?
- How to implement componentDidMount with hooks in React to be in line with the EsLint rule "react-hooks/exhaustive-deps": "warn"?
- Property 'location' does not exist on type 'typeof window'
- How can I add this main js to the template tags without it throwing a tag error?
- Event handler not picking up correct state value
- Fill array with random picture from url that gives random picutres
- React tag script are called only the first time
- Can't setup nginx proxy to docker container with react
- Cannot remove an event listener outside useEffect
- Data returned from server renders on the page when refreshed (but not when I change to its route)
- How to pass arguments to methods inside class components in React?