As a newcomer to Typescript (and Javascript), I've been experimenting with classes. My goal is to create an object that can be filled with similar entries while maintaining type safety in a concise manner.
Here is the code snippet I came up with:
let testFixture: Fixture = (() => {
let stringPrefix = 'TEST BaseEventDTO';
let result = {}; // The object will become a "Fixture".
['id', 'name', 'location'].forEach(element => {
result[`${element}`] = generateId(`${stringPrefix} ${element}`);
});
return result;
})();
This code defines Fixtures with mandatory string fields id
, name
, and location
. It's essential for all of them to include the stringPrefix before the field name, as demonstrated in the foreach loop. My aim is to avoid repeating the same information multiple times, such as the prefix or field names. However, this approach triggers a warning from VSCode stating that
Type {} is missing the following properties of Type 'Fixture': 'id', 'name', and 'location'
.
I'm curious if there is a preferred or effective method to achieve this task.
To clarify, I used an anonymous function to keep the stringPrefix
variable local.
EDIT: I managed to resolve the error by changing return result;
to return <Fixture>result;
. Nonetheless, I am documenting this in case my solution has drawbacks, or if there are better alternatives available.
Just to provide further clarity, the desired outcome for 'result' should ultimately resemble this:
let result = {
id: generateID(`${stringPrefix} id`),
name: generateID(`${stringPrefix} name`),
location: generateID(`${stringPrefix} location`)
}
Afterwards, the object would be cast into a 'Fixture' type.