I am working on typing existing javascript files in typescript for my business.
Here is a sample object:
[
{
// The column names givenName, familyName, and picture are ones of examples.
"givenName": {
"text": "Foo",
"type": "text"
},
"familyName": {
"text": "Bar",
"type": "text"
},
"picture": {
"text": "abc.png",
"type": "image",
"thumbnail": "https://example.com/thumbnail/sample.png"
},
// The following two properties are paths to the PDF and thumbnail generated from the above information.
"pdf62882329b9baf800217efe7c": "https://example.com/pdf/genarated_pdf.pdf",
"thumbnail62882329b9baf800217efe7c": [
"https://example.com/thumbnail/head.png",
"https://example.com/thumbnail/tail.png"
]
},
{
// ... (The structure is the same as above object.)
}, // ...
]
I would like to type the object part as follows:
type Row = {
[headerKey: string]: {
text: string;
type: "text";
} | {
text: string;
type: "image";
thumbnail: string;
};
// The following two properties are the paths to the generated PDF and thumbnails.
// The reason for concatenating the id is to avoid name conflicts when the column names "pdf" and "thumbnail" come in the column name.
// (Since the string for id is randomly generated, I believe it is unlikely that this string will be used for the column name.)
pdf+id: string; // path to the generated PDF
thumbnail+id: [string, string]; // path to the generated thumbnail (It have two elements because the image has two sides.)
};
And I used Template literal types, typed as follows:
type Row = {
[headerKey: string]: {
text: string;
type: "text";
} | {
text: string;
type: "image";
thumbnail: string;
};
[pdfKey: `pdf${string}`]: string;
[thumbnailKey: `thumbnail${string}`]: [string, string];
};
But it doesn't work as expected. Is there any way to successfully type this object?