I have this basic type def:
export interface Person {
name: string;
age: number;
created: Date;
...
}
The data with this type comes from a json file.
JSON.parse does not produce Date from string, so I was thinking to use the 2nd "reviver" parameter which allows you to modify the value that is being parsed based on the key.
So first I create a list of props that need to be modified:
const deserializeMap: Mapper = {
created: v => new Date(v)
}
But I am not sure how to define the "Mapper" type.
it should be something like this:
type Mapper = {
<K extends keyof Person >K: (value: any) => Person [K]
};
so depending on what property I define, the value returned by the function has to match the type of the property from the Person class
>Solution :
You can use a mapped type to define the mapper type:
type Mapper = {
[K in keyof Person]: (value: any) => Person[K];
};
and then you can say that your deserializeMap satisfies a Partial<Mapper>:
const deserializeMap = {
created: v => new Date(v)
} satisfies Partial<Mapper>;
Depending on how you use deserializeMap, you may want to use a type annotation instead:
const deserializeMap: Partial<Mapper> = {
created: v => new Date(v)
};