Home > other >  Function with argument won't display in VS Code
Function with argument won't display in VS Code

Time:01-02

Goal:
Enable to use function Test2 with argument value "Test 2" and then to be displayed without any error in Visual Studio Code.

Problem:
When I apply the code "<Test2 thename={'Test 2'} />" and "function Test2", it shows an error saying

Compiled with problems:X

ERROR in src/App.tsx:11:18

TS7006: Parameter 'props' implicitly has an 'any' type.
     9 |   }
    10 |
  > 11 |   function Test2(props) {
       |                  ^^^^^
    12 |     return <h1>{props.thename} works!</h1>;
    13 |   }
    14 |

What part am I missing order to be working in VS code?

Info:
*Newbie in ReactTS
*It works for stackblitz but not for VS Code (Function with argument won't display)
*https://stackblitz.com/edit/react-ts-atrrsi?file=index.tsx

Thank you!

import React from 'react';
import logo from './logo.svg';
import './App.css';

export default function App() {

  function Test1() {
    return <h1>Test 1 works!</h1>;
  }

  function Test2(props) {
    return <h1>{props.thename} works!</h1>;
  }

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>

        <Test1 />
        <Test2 thename={'Test 2'} />        
      </header>
    </div>
  );
}

CodePudding user response:

In Typescript if you don't assign a type of an argument for a function it automatically will be assigned as any. But this type asignent will throw error if you won't change the default configs of typescript. This is not limited to jsx, it's just how TS works.

There are a few ways to overcome this issue.

  1. Define the interface for your argument and set is as type:
interface Props {
    thename: string;
}

function Test2(props: Props) {
    return <h1>{props.thename} works!</h1>;
}

This is the best option.

  1. Assign any type explicitly:
function Test2(props: any) {
    return <h1>{props.thename} works!</h1>;
}
  1. Change tsconfig.json and allow implicit any.

PS: Components should not be defined inside another components. Every component should be defined on the top level (just like your App component).

  • Related