I need help figuring out how to import a raw JSON data file and automatically convert my date string to a date object within my type.
In my type definition:
export type Client = {
id: number;
first_name: string;
last_name: string;
dob: Date;
}
The contents of my client.json
file are:
[{"id":1,"first_name":"Alasdair","last_name":"Kingman","dob":"1969-07-11"},
{"id":2,"first_name":"Ursulina","last_name":"Skellion","dob":"1986-01-08"}]
My client.ts
file includes the following:
import {Client} from "./model";
import clients_raw from "../mock-data/clients/clients.json" with {type: "json"}
const clients: Client[] = clients_raw as Client[];
Using the as
operator is causing an error:
TS2352: Conversion of type
....
Types of property dob are incompatible.
Type string is not comparable to type Date
Is there a way to import the dob field directly as a Date object? Or should I manually handle the conversion? Although, this manual approach seems inefficient as it will iterate over the entire array whenever the module is loaded.
const clients: Client[] = clients_raw.map((client) : Client => {
return {...client, dob: new Date(client.dob) }
});
I'm hoping there's a more efficient solution available?