what I need is:
- typescirpt understood that the first element of each internal array is a prop create (therefore with autocomplete)
- that the second element of each internal array was typed with the object type passed (realHero) with the prop of the first parameter, therefore, if I pass
["name", ...
] typescript must accept onlyreader<string>
sincerealHero["name"]
isstring
- that the final result at the level of API did not change
this is my code
enum HeroSex {
male,
female,
unknown,
}
interface Hero {
name: string;
age: number;
sex: HeroSex;
}
type reader<T> = (value: T) => void;
//the problem is 99% here :(
type readers<T, K extends keyof T> = [prop: K, readerFn: reader<T[K]>];
const readString: reader<string> = (value: string) => {
console.log(`the string is ${value}`);
};
const readNumber: reader<number> = (value: number) => {
console.log(`the number is ${value.toFixed()}`);
};
const readHeroSex: reader<HeroSex> = (value: HeroSex) => {
console.log(`the enum is ${value.toString()}`);
};
const readProperties = <T>(Obj: T, readers: readers<T, keyof T>[]) => {
for (const [prop, reader] of readers) {
reader(Obj[prop]);
}
};
const realHero: Hero = {
name: "batman",
age: 38,
sex: HeroSex.male,
};
//expected result (for the moment is not working)
readProperties(realHero, [
["age", readNumber], //ok
["name", readString], //ok
["sex", readNumber], //typescript error
]);
readProperties(realHero, [
["age", readNumber], //ok
["name", readString], //ok
["sex", readHeroSex], //ok
]);