Within my class structure, I have the following:
class Collection<ID extends string | number> {
entries: ID[];
constructor(private readonly useStringIds: boolean) {}
getIds(): ID[] {
return entries.map((entry) => entry.id);
}
handleResults(results: ObjectWithNumberId[]) {
if (this.useStringIds) {
this.entries = results.map((result) => ({
...result,
id: result.id.toString(),
}));
} else {
this.entries = results;
}
}
}
There are scenarios where the id
field may remain a number
, while at other times it needs to be converted.
Is there a way to simplify this in TypeScript so that by just passing an argument to the class, the generic type automatically aligns with the argument passed into the constructor (
const c = new Collection<string>(true);
)?