Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'unknown'

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading