Search code examples
typescript

Not getting auto completion for generic type arguments


I have this function

function updateProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
  obj[key] = value;
}

And I have this interface and object:

interface ExampleObject {
  a: boolean;
  b: number;
  c: string;
}

const example: ExampleObject = { a: false, b: 10, c: 'Hello' };

And I am calling this function:

updateProperty<ExampleObject, 'a'>(example, 'a', true);
updateProperty<ExampleObject, 'b'>(example, 'b', 20);
updateProperty<ExampleObject, 'c'>(example, 'c', 'World');

My code has no problems, and I get types verifyed correctly, however, I am missing the feature for autocompletion in vscode for the generic type parameters for the K type.

In other words while writing those I don't get autocompletion for this field:

updateProperty<ExampleObject, 'a'>(e...
                              👆

Here's the playground


Solution

  • This is a missing feature of TypeScript, as requested in microsoft/TypeScript#28662. It's a fairly longstanding feature request and doesn't seem to have much community support (only a few dozen upvotes) so it's not likely to be implemented anytime soon. For now you'll either need to put up with it, or work around it.

    By far the easiest workaround for your example code is to just not manually specify the generic type arguments. Let TypeScript infer them, which is by far the most common way generic function calls occur:

    updateProperty(example, 'a', true);
    // T inferred as ExampleObject, K inferred as "a"
    

    Even though K doesn't give you autocomplete, key does:

    updateProperty(example, |
    //                      ^ 🔧 "a"
    //                      ^ 🔧 "b"
    //                      ^ 🔧 "c"
    

    Playground link to code