如何使用“() => void”根据 tslint 对函数进行类型定义?

How to typedef a function according to tslint with "() => void"?

我有一个函数需要打字:

const checkIfTagNeedsToBeCounted = (listOfTags: string[]): boolean => {
  const tagsToExcludeFromCounting: string[] = [
    "DoNotCount",
  ];

  const excludedTagFound: boolean = listOfTags.some(
    (singleTag) => tagsToExcludeFromCounting.includes(singleTag),
  );

  return !excludedTagFound;
};

做的时候

const checkIfTagNeedsToBeCounted: Function = ...

tslint 正在模拟:

不要使用 'Function' 作为类型。避免使用 Function 类型。首选特定的函数类型,例如 () => void。 (禁令类型)

到目前为止我一直忽略

的问题
// tslint:disable-next-line: ban-types
const checkIfTagNeedsToBeCounted: Function = (listOfTags: string[]): boolean => {

但我很想知道根据 tslint 对函数进行类型定义的正确方法是什么?

Function确实不够精确

正如打字稿告诉您的那样,您需要准确定义要使用的函数的原型。

您将获得自动完成和错误检测(错误的参数...等)。

你有两种方法来处理这个问题,要么让 typescript 推断函数的类型。

要么你自己定义函数的类型。

注意:如果typescript无法正确推断(当你经常使用any时就是这种情况),或者如果你想重用类型,请选择第二个选项.


你的情况:

const checkIfTagNeedsToBeCounted: (listOfTags:string[]) => boolean = (listOfTags: string[]): boolean => {
   // ...
};

如果要重用函数类型:

type MyFunction = (listOfTags: string[]) => boolean;

const checkIfTagNeedsToBeCounted: MyFunction = (listOfTags: string[]): boolean => {
   // ...
};