Is there a way for the compiler to verify the type of value in this scenario?
type SomeType = {
foo: string[];
bar: number | null;
};
type SomeTypeChanges<K extends keyof SomeType = keyof SomeType> = {
key: K;
value: SomeType[K]
};
declare function baz(changes: SomeTypeChanges);
// There should be an error in both cases
baz({key: "foo", value: 1}); // type of value must be string[]
baz({key: "bar", value: ["a", "b"]}) // type of value must be number | null
This situation is actually more complex because I am exporting this from an external library:
export interface MyEvent<Payload> {
(payload: Payload): Payload;
}
export declare function createEvent<E = void>(eventName?: string): MyEvent<E>;
I am trying to use it like this:
const myEvent = createEvent<SomeTypeChanges<keyof SomeType>>();
myEvent({ key: "foo", value: 1 });
^^^^^
However, I am unable to add the type parameters to the function. This poses a challenge.