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

Time:10-28


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?

CodePudding user response:

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
}
  • Related