I have a function I want to reuse that is applicable on multiple properties of a custom type. Something like this:
interface MyType {
prop1: string;
prop2: number;
}
type MyTypeKey = keyof MyType;
const testValue = (
obj: MyType,
property: MyTypeKey,
value: any, // <-- what type should go here?
) => {
if (obj[property] === value) {
console.log("do something");
}
}
testValue({prop1: "a", prop2: 1}, "prop1", "okay"); // should be okay
testValue({prop1: "a", prop2: 1}, "prop2", "oops"); // should be error
But I don't know how to do this since I don't know the type of the property value. How can I solve this?
(I am new to javascript/typescript, so forgive me for small typos and constructions and bad practices)
Use a generic argument to indicate the key. From that key you can look it up on MyType to get the associated value's type, and require that the value argument to the generic function be that type.
interface MyType {
prop1: string;
prop2: number;
}
const testValue = <K extends keyof MyType>(
obj: MyType,
property: K,
value: MyType[K],
) => {
if (obj[property] === value) {
// ...
}
}
declare const obj: MyType;
// OK
testValue(obj, 'prop2', 3);
// Not OK
testValue(obj, 'prop2', 'a');
For a more flexible function that can validate any sort of object, without hard-coding MyType into it, make another generic type for the object.
const testValue = <O extends object, K extends keyof O>(
obj: O,
property: K,
value: O[K],
) => {
if (obj[property] === value) {
// ...
}
}