Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply constraints to type based on the key-value of another type

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
};

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading