0

We should be able to use in keyof to index an Array since the index are just numbers. In which case, the following code should work?

Does anybody have any insight into what I'm missing?

Playground link

function test 
   <array_T extends {key: string}[]>(input:array_T) : 
     {[index in keyof array_T]: array_T[index]['key']}
  
  {
    return '' as any;
  }

***ERROR***
Type '"key"' cannot be used to index type 'array_T[index]'.

1 Answer 1

1

This is a known limitation/bug in TypeScript. See microsoft/TypeScript#27995 for more information. While mapping over an array/tuple input type does result in an array/tuple output type, inside the mapped type's clause itself the compiler mistakenly thinks that I in keyof T is iterating over all keys of T, even the array methods and length.

For now you have to convince the compiler that T[I] is assignable to T[number], the element type of the array. You can use the Extract utility type to do this:

function test<T extends { key: string }[]>(input: T): {
    [I in keyof T]: Extract<T[I], T[number]>['key']
} {
    return '' as any;
}

Playground link to code

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.