minjae kim
minjae kim

Reputation: 139

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


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?

Upvotes: 0

Views: 1667

Answers (1)

Mack
Mack

Reputation: 771

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
}

Upvotes: 4

Related Questions