Home > Back-end >  Element implicitly has an 'any' type because expression of type '0' can't b
Element implicitly has an 'any' type because expression of type '0' can't b

Time:07-27

I am getting an error as : how to generalise a return type?

    Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'unknown'.
  Property '0' does not exist on type 'unknown'.(7053)

ts code :

function ReturnFist<Type>(items:Type): Type {
    return items[0]; //error is here
}


const item1 = [1,2,3,4,5];
const item2 = ['a','b','c'];
const item3 = [true, false, true, true];
const item4 = [{name:'one'}, {name:'two'}, {name:'thre'}, {name:'four'}];

const result1 = ReturnFist<number[]>(item1);
const result2 = ReturnFist<string[]>(item2);
const result3 = ReturnFist<boolean[]>(item3);
const result4 = ReturnFist<boolean[]>(item3);

Live Demo

CodePudding user response:

You need to further constrain your generic type parameter:

function ReturnFirst<Type extends Array<any>>(items: Type): Type[number] {
  return items[0];
}

There are more elegant ways to write this though:

function ReturnFirst<Type>(items: Type[]): Type {
    return items[0];
}


const item1 = [1, 2, 3, 4, 5];
const item2 = ['a', 'b', 'c'];
const item3 = [true, false, true, true];
const item4 = [{name:'one'}, {name:'two'}, {name:'three'}, {name:'four'}];

const result1 = ReturnFirst(item1);
const result2 = ReturnFirst(item2);
const result3 = ReturnFirst(item3);
const result4 = ReturnFirst(item4);
  • Related