Search code examples
javascriptreactjstypescripttypescript-genericsreact-typescript

how to mark a function paramter Type as Function in TypeScript?


I'm learning typescript and I don't know how to mark a function paramter as function. For example in this code I'm passing a setState function via props to children component.

const SelectCity = ({ onShowCity }: Function): JSX.Element => {}

This Function type return an error Property 'onShowCity' does not exist on type 'Function'

I tried function(lowercase) as will and returned another error Cannot find name 'function'. Did you mean 'Function'?

this is my implomention. showCity is a variable with a false value; i passed the setShowCity as a paramter so its a function and accepts boolean.

  const [showCity, setShowCity] = useState(false);

          {showCity ? (
            <SelectCity onShowCity={setShowCity} />
          ) : (
            <SelectState onShowCity={setShowCity} />
          )}

How should I do this ?

and another question JSX.Element is the correct Type for functional component return?


Solution

  • You have two problems.

    1. The parameter is not a function. It is an object where the value of one of the properties is a function.
    2. Function types are well documented in the manual and need the arguments and return value defining.

    So (and I'm guessing about the shape of your particular function here):

    type MyProps = {
        onShowCity(foo: string, bar: number): void; 
    };
    
    const SelectCity = ({ onShowCity }: MyProps): JSX.Element => {}