UPDATE: The issue is a limitation of TypeScript, the issue is on Typescripts GitHub now: https://github.com/microsoft/TypeScript/issues/47440
I currently have the following code:
class Table<T,> {
constructor(records: T[], columns: Column<T>[]) { ... }
}
class Column<T> {
constructor(name: string, transformer: (item: T) => string) { ... }
addTooltip(transformer: (item: T) => string): this { ... }
}
class Building {
constructor (public name: string) {}
}
const buildings = [
new Building("test"),
new Building("station")
];
I want to create a table, without having to specify that T
is of type Building
.
This works so far, because typescript can infer the type from the buildings array and it works. Even in the transformer
of the Column, I still get type suggestions.
const table = new Table(buildings, [
new Column("Name", building => building.name)
]);
But when I use addTooltip
, typescript can't figure out what T
is and completely freaks out, because the Column
assumes that T
is unknown
.
const table = new Table(buildings, [
new Column("Name", building => building.name),
new Column("Name", building => building.name).addTooltip(t => t.name)
]);
Is there a way to tell TypeScript to use the type of its records
constructor parameter as a source for T, ignoring what the columns think T
is - without using new Table<Building>(...)
? I know that we could use columns: Column<any>[]
, but then the type checking in the Columns would not work.
new Column("Name", building => building.name)
should beColumn<Building>
to my mind, so callingaddTooltip
on it should know it's aBuilding
. But I don't write the TypeScript compiler and I'm sure it's more complicated than that. :-DaddTooltip()
, TS can't really figure out the type parameter for the constructor, as it'd have to infer things backwards.Table -> addTooltip() -> Building
, but asaddTooltip()
depends onBuilding
, this fails.