returns 列表大小的通用函数中的 no-explicit-any

no-explicit-any in generic function which returns list size

我有一个简单的函数returns数组的长度

const test = (list: any[]) => list.length;

产生 eslint 错误:

no-explicit-any: Unexpected any. Specify a different type. (javascript-eslint)

用 TypeScript 编写此函数的正确方法是什么?

这似乎与 es linters 运行 命令文件的规则有关。但是,您可以将其关闭:

rules: {
    "@typescript-eslint/no-explicit-any": "off"
  }

但是,我强烈建议您在 Typescript 中使用推理规则。 any 类型的使用违背了 TypeScript 的目的。但是,您可以尝试以下操作:

function test <Type> (list: Type[]): number {
    return list.length;
}    

console.log(test([1, 2, 3, 4]));
console.log(test(["1", "2", "3", "4"]));
console.log(test([1, "2", 3, "4"]));

使用泛型:

const test = <T>(list: T[]): number => list.length;

然后你可以这样调用函数:

test([1, 2, 3]) // or test<number>([1, 2, 3]);
test(["s1", "s2", "s3"]); // or test<string>(["s1", "s2", "s3"]);
test([{ 
  key1: 'k1', 
  key2: 'k2',
}]);