Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript – resolve function argument type during invocation

const func = <T>(
  obj: T,
  attr: keyof T,
  arr: T[typeof attr][],
) => {
}

const obj = {foo: 1, bar: true};

func(obj, 'foo', [1]);
func(obj, 'bar', [1]); // shouln't be ok
func(obj, 'foo', [true]); // shouln't be ok
func(obj, 'bar', [true]);

How do I need arr argument type to be defined so that TS would correctly resolve its type during func invocation so that it wouldn’t always be number | boolean but rather depend on actual attr?

Playground link.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You do it by ensuring you’re getting the specific type of the property identified by the key by making the key type generic as well as the object type:

const func = <ObjectType, KeyType extends keyof ObjectType>(
    obj: ObjectType,
    attr: KeyType,
    arr: ObjectType[KeyType][],
) => {
    console.log(obj, attr, arr);
};

const obj = {foo: 1, bar: true};

func(obj, "foo", [1]);
func(obj, "bar", [1]);    // <== Error as desired
func(obj, "foo", [true]); // <== Error as desired
func(obj, "bar", [true]);

Playground link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading