I've encountered a compilation/type error while attempting to implement something similar to the code snippet below.
interface IEntityLookup {
[Entity.PERSON]: IPersonLookup
[Entity.COMPANY]: ICompanyLookup
}
interface ISubEntity {
[Entity.PERSON]: People
[Entity.COMPANY]: Companies
}
function mapEntity<E extends Entity, S extends ISubEntity[E]>(
entityType: E,
subEntity: S
): IEntityLookup[E][S] | null {
switch (entityType) {
case Entity.PERSON:
return mapPerson(subEntity)
case Entity.Company:
return mapCompany(subEntity)
}
}
The area of interest is in the mapEntity
function where I aim to return IEntityLookup[E][S]
. Is achieving this possible in Typescript?
Below are the complete definitions:
enum Companies {
TESLA = "tesla",
MICROSOFT = "microsoft",
}
interface ITesla {
id: string
cars: number
}
interface IMicrosoft {
id: string
software: string
}
enum People {
ELON_MUSK = "elon-musk",
BILL_GATES = "bill-gates",
}
interface IElonMusk {
id: string
rockets: number
}
interface IBillGates {
id: string
windows_version: string
}
interface ICompanyLookup {
[Companies.TESLA]: ITesla
[Companies.MICROSOFT]: IMicrosoft
}
interface IPersonLookup {
[People.ELON_MUSK]: IElonMusk
[People.BILL_GATES]: IBillGates
}
function mapPerson<T extends People>(
personType: T
): IPersonLookup[T] | null {
switch (personType) {
case People.ELON_MUSK:
return {id: "1", rockets: 1000} as IPersonLookup[T]
case People.BILL_GATES:
return {id: "1", windows_version: "98"} as IPersonLookup[T]
default:
return null
}
}
function mapCompany<T extends Companies>(
companyType: T
): ICompanyLookup[T] | null {
switch (companyType) {
case Companies.TESLA:
return {id: "1", cars: 1000} as ICompanyLookup[T]
case Companies.MICROSOFT:
return {id: "1", software: "98"} as ICompanyLookup[T]
default:
return null
}
}
enum Entity {
PERSON = "person",
COMPANY = "company",
}
interface IEntityLookup {
[Entity.PERSON]: IPersonLookup
[Entity.COMPANY]: ICompanyLookup
}
interface ISubEntity {
[Entity.PERSON]: People
[Entity.COMPANY]: Companies
}
function mapEntity<E extends Entity, S extends ISubEntity[E]>(
entityType: E,
subEntity: S
): IEntityLookup[E][S] | null {
switch (entityType) {
case Entity.PERSON:
return mapPerson(subEntity)
case Entity.Company:
return mapCompany(subEntity)
}
}