Home > front end >  how to mark a function paramter Type as Function in TypeScript?
how to mark a function paramter Type as Function in TypeScript?

Time:07-23

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?

CodePudding user response:

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 => {}

CodePudding user response:

You need to

  1. remember that you need to type all of the props (though you only have one now), i.e. the props' type is an object type, not a single function
  2. be more specific about the function's type.

For instance, if the handler would accept a string argument and return nothing, i.e.

function handleShowCity(city: string) { 
  alert(`Nice, ${city} is beautiful this time of the year`);
}

you'd type the props as

function SelectCity({ onShowCity }: {onShowCity: (city: string) => void}) { ... }

(You don't need to necessarily explicitly specify the return type anyway.)

You can also separate the type into an interface so it can be e.g. exported:

interface SelectCityProps {
  onShowCity: (city: string) => void;
}

function SelectCity({ onShowCity }: SelectCityProps) { ... }
  • Related