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

Viewed 858

I have a simple function which returns array's length

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

Which generates eslint error:

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

What would be the correct way to write this function in TypeScript?

2 Answers

Use generics:

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

Then you can call function like:

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',
}]);

This appears to be linked to the es linters run command file's rules. You can, however, turn it off:

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

However, I strongly advise you to use inference rules in Typescript. Use of any types defeats the purpose of TypeScript. You could, however, try the following:

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"]));
Related