score:1

Accepted answer

for the intellisense part of the question, it looks like the completion list just doesn't include keyof a when examining keyof b when b extends a. it would be nice if it did, but it doesn't. such a change has been suggested. if you want to see this happen you might want to go to that github issue and give it your 👍 or describe your use case if you think it is both compelling and different from what's already there.

for now the workaround could be to change the constraint to be k extends keyof t | keyof myitem. since keyof t already must include keyof myitem, the additional union of keyof myitem doesn't change anything in terms of what types are valid specifications for k. but it does bring back the intellisense autocompletion list you expect.


for the "correct type for value parameter" part of the question, i think i need more elaboration on what you mean. but do be warned: if t extends myitem, then t["name"] might be a narrower type than myitem["name"]. imagine:

interface myitem {
    name: string;
}

export function mycomponent<t extends myitem>() {

    function handleonchange<k extends keyof t | keyof myitem>(key: k) {
        return function (value: t[k]) { }
    }

    handleonchange("name")("fred"); // wait a minute

}

typescript allows you to call handleonchange("name")(xxx) with any string as xxx, even though this is not safe. observe:

interface myitemnamedbob extends myitem {
    name: "bob";
}

mycomponent<myitemnamedbob>(); // ?

a value of type myitemnamedbob has the literal string "bob" as the name at the type level. it cannot be changed to "fred". handleonchange("name") for a generic t that extends myitem can't really safely accept anything at all. in practice this might not matter, but you should be careful, since the compiler isn't always.


okay, hope that helps; good luck!

link to code

score:0

have you tried doing k keyof t instead of k extends keyof t?


Related Query

More Query from same tag