Typescript 'T' cannot be used to index type? But T is "keyof" target type

Issue


type foo = {
    asd:""
}

interface FOOS<T = keyof foo> extends foo {
    copy(key: T): foo[T]// error
}

Type 'T' cannot be used to index type 'foo'.

How can I tell typescript that this T can be used as a key for that type?

Solution

Your generic type has a default of keyof foo, but someone could still instantiate it with any unrelated type: FOOS<string>, FOOS<unknown> etc.

Try placing a restriction on T:

interface FOOS<T extends keyof foo= keyof foo> extends foo {
    copy(key: T): foo[T]// error
}

Answered By – Mack

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published