简体   繁体   English

如何在 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.例如,在这段代码中,我通过 props 将 setState 函数传递给子组件。

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

This Function type return an error Property 'onShowCity' does not exist on type 'Function'Function类型返回错误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'?我按原样尝试了函数(小写)并返回了另一个错误Cannot find name 'function'. Did you mean 'Function'? Cannot find name 'function'. Did you mean 'Function'?

this is my implomention.这是我的实现。 showCity is a variable with a false value; showCity 是一个具有 false 值的变量; i passed the setShowCity as a paramter so its a function and accepts boolean.我将 setShowCity 作为参数传递,因此它是一个函数并接受布尔值。

  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?另一个问题JSX.Element是功能组件返回的正确类型吗?

You need to你需要

  1. remember that you need to type all of the props (though you only have one now), ie 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, ie例如,如果处理程序接受一个字符串参数并且什么都不返回,即

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 eg exported:您还可以将类型分离到一个接口中,以便可以将其导出:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM