Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript | Warning about Missing Return Type of function, ESLint

People also ask

How do you find the return type of a function in TypeScript?

Use the ReturnType utility type to get the return type of a function in TypeScript, e.g. type T = ReturnType<typeof myFunction> . The ReturnType utility type constructs a type that consists of the return type of the provided function type.

How do you define return type in Arrow?

Set the return type of an arrow function in TypeScript # You can set the return type of an arrow function in TypeScript right after its parameters, e.g. const greet = (name: string): string => {} . Once a function's return type is set, the type checker alerts us if the function returns a value of a different type.

What is return type in TypeScript?

Function return type in TypeScript is nothing but the value which we want to return from the function. Function return type used when we return value from the function. We can return any type of value from the function or nothing at all from the function in TypeScript.

What is the return type of a react component?

ReactNode Type in TypeScript The type is returned by React class components' render() function. It can be a ReactElement , ReactFragment , ReactText , a string, a Boolean, and other falsy values in JavaScript, such as undefined or null .


I'd recommend using the types provided by react; they'll include the return type. If you're on the version 16.8.0 or later of react, do this:

const Component: React.FunctionComponent<Props> = (props) => (

Or use the shorthand:

const Component: React.FC<Props> = (props) => (

Prior to 16.8, you'd instead do:

const Component: React.SFC<Props> = (props) => (

Where SFC stands for "stateless functional component". They changed the name, since function components are no longer necessarily stateless.


For a function return type it goes after the arguments:

({ prop }: Props & T): JSX.Element => {}

JSX.Element is what TypeScript will infer, it's a pretty safe bet.

If you're curious, you should be able to see what TypeScript infers as the return type by hovering over Component, this will show the entire signature.


This is how I usually declare a component using typescript:

import * as React from 'react';

type MyComponentProps = {
  myStringProp: String,
  myOtherStringProp: String
};

const MyComponent: React.FunctionComponent<MyComponentProps> = ({ myStringProp, myOtherStringProp }): JSX.Element => {
  return (
    <div>
      <h1>This is My Component</h1>
    </div>
  );
};


export default MyComponent;

If you use @types/react you don't have to provide return types for React components. You can disable this rule for react components like this. Just add this to your .eslintrc.js:

  overrides: [
    {
      files: ['*.jsx', '*.tsx'],
      rules: {
        '@typescript-eslint/explicit-module-boundary-types': ['off'],
      },
    },
  ],