Home > Net >  Element implicitly has an 'any' type because expression of type '"length"&#
Element implicitly has an 'any' type because expression of type '"length"&#

Time:03-28

 function getLength<T>(arg: T): number {
 if (!arg.hasOwnProperty("length")) {
   return 0;
 }
 return arg["length"];
}

Here I am not able to access the value through bracket notation, this works in javascript but typescript is giving me issues on this.

enter image description here

This is the error in terminal thats running ts-node-dev

CodePudding user response:

Using type predicates

type HasLength = { length: number };

function hasLength(arg: any): arg is HasLength {
  return (arg as HasLength).length !== undefined;
}

function getLength<T>(arg: T): number {
  if (arg && hasLength(arg)) {
    return arg.length;
  } else {
    return 0;
  }
}

console.log(getLength(3)); //0
console.log(getLength("333")); //3
console.log(getLength({ "1": 1, "2": 2, "3": 3 })); //0
console.log(getLength({ "1": 1, "2": 2, "3": 3, length: 3 })); //3
console.log(getLength([1, 2, 3])); //3
console.log(getLength(true)); //0
console.log(getLength(undefined)); //0
console.log(getLength(null)); //0

The reason for using arg && hasLength(arg) instead of hasLength(arg) is that calling undefined.length or null.length will throw an error.

CodePudding user response:

in your function you're using a generic type named T and by default, it's defined as any, and any does not have a length property so you should extend your type so it should be defined in your generic like the following:

function getLength<T extends { length?: number, [key: string]: any }>(arg: T): number {
    if (typeof arg.length === 'undefined') {
        return 0;
    }
    return arg["length"];
}
console.log(getLength([1, 3, 4])) // --> 3
console.log(getLength({ length: 4 })) // --> 4
console.log(getLength({ a: 1 })) // --> 0
  • Related