In my code, there is a function named isDone()
that will return data from either an array of hashes or a dictionary of hashes:
public async isDone() {
this.startDelayedTasks();
await Promise.all(this._tasks);
const hadErrors = this._failed.length > 0 ? true : false;
if (hadErrors) {
throw new ParallelError(this);
}
return this._resultType === "hash"
? (this._results as IDictionary<T>)
: hashToArray<IParallelArrayType<T>>(this._results) as IParallelArrayType<T>[];
}
The interface for IParallelArrayType looks like this:
export interface IParallelArrayType<T> {
name: string;
value: T;
}
If consumers request the array type, they might want to use functions like map
, filter
, or length
. However, since the return type could be different, it can lead to errors like this:
https://i.sstatic.net/0Lvhl.png
To work around this issue, consumers can add a check like this:
if(Array.isArray(results)) {
expect(results.length).to.equal(4);
}
It would be helpful if there was a way to avoid burdening the consumer with handling this. One idea could be implementing a tagged union type and using a Symbol for identifying the property.
This approach seems promising, but I also want to make sure that consumers of the hash/dictionary return type do not see the Symbol key when iterating through the object using Object.keys(dictionary)
. Is there a solution to achieve this, or am I delving too deep into the runtime environment?