My attempt to create a partial helper function in Typescript led me to an incorrect version that went unnoticed by Typescript:
Typescript version: 5.2.2
type A = { a: number; b: string };
// incorrect
const buildPartialBad = (key: keyof A, val: A[keyof A]): Partial<A> => ({ [key]: val });
const test1 = buildPartialBad('a', 'hello'); // allows creation of an invalid object
// correct
const buildPartialGood = <K extends keyof A>(key: K, val: A[K]): Partial<A> => ({ [key]: val });
const test2 = buildPartialGood('a', 'hello'); // compile error: Argument of type 'string' is not assignable to parameter of type 'number'
I am puzzled as to why the buildPartialBad function did not trigger any errors.
While searching on StackOverflow and GitHub for similar Partial-related issues, I couldn't find an exact match. It seems like such a simple oversight that it's hard to believe it could be a bug in TS. Perhaps I'm just not fully awake :)
If anyone has an explanation, I would greatly appreciate it. Thank you