Issue
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?
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]);
Answered By - T.J. Crowder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.