Skip to content

Compilation failure with Generic, Promis and ReturnType #40762

Closed
@ilchenkoArtem

Description

@ilchenkoArtem

TypeScript Version: 3.7.x-dev.201xxxxx

Search Terms:
Promise, ReturnType, Generic
Code

interface IBusinessUnitModel {
  parentId?: number,
  environmentId?: number
}

interface IEnvironmentModel {
  guid?: string,
  readonly inheritance?: string,
  userDomainId?: number,
  friendlyName?: string
}

interface IDictionaries {
  environment: IEnvironmentModel[];
  businessUnit: IBusinessUnitModel[];
}

type DictionaryMethodsType = {
  [key in keyof IDictionaries]: () => Promise<IDictionaries[key]>
};

async function loadDictionary<T>(url:string): Promise<T[]> {
  const response = await fetch(`/api/${url}`);
  return await response.json()
}

const loadDictionaryMethods:DictionaryMethodsType = {
  environment: () => loadDictionary<IEnvironmentModel>('environments'),
  businessUnit: () => loadDictionary<IBusinessUnitModel>('businessUnit'),
}

export const loadDictionaryByName =
  <N extends keyof DictionaryMethodsType>(name: N):Promise<ReturnType<DictionaryMethodsType[N]>> => loadDictionaryMethods[name]()

Expected behavior:
Compilation successful

Actual behavior:
Compilation failure with error:

Type 'Promise<IEnvironmentModel[]> | Promise<IBusinessUnitModel[]>' is not assignable to type 'Promise<ReturnType<DictionaryMethodsType[N]>>'. Type 'Promise<IEnvironmentModel[]>' is not assignable to type 'Promise<ReturnType<DictionaryMethodsType[N]>>'. Type 'IEnvironmentModel[]' is not assignable to type 'ReturnType<DictionaryMethodsType[N]>'.

Playground Link:
https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgJICECuBnUFvYCqIwYAsgPYAmEANsgN4BQyyADnFBOKlQPwAuZCEwBbAEbQANC2TcAbsCgUQo7mF6DhYyVCYBfJk1CRYiFKgCiIRctXrKNes1YBzTMH5DsYKKFcyrFxwVCq0AJ7IoAAW0KRwIEhaPn4gAbI40AAiFKJwoJpCIhLSsjB+3FQRAHJwasm+-gZGJtDwSGhZwAhgwCqcwPiMsgpKKmrgQlY2Y-bgjnQA2gC6ANyy4jh4BMSkU1i4IPhEJOTUS2vNTGDhbChdPX0gnOFkEGDR1NgAKrcoALzDViLADWEEioGQYPCFBgnW6vX6FWwyyEAAoAJTIf4APmQAAVlKJgNgIAAeVAPRHPZGg8HLHEGdZMODYcKJZAwTCJanIWgUEJUp4vMnfHFozBQWgCFL+DFCQm5Enk74rPEuZAIFQ+ZBcbBsbUA5BwADu+TAnPeCGiaIABgB6OBsYD2gAkDEltH0tox6yC70lIGNZtIuvwBpApIAdAArbAqTFXLWRi38wUI4VQV7vT5UbACIVI7MfL6-O7YoFyGZ2CZgdFY3F8gVUQs08IU6y2cYOc60cUAclGNfU2H7GMCyE2h2OuzryEx2LxaZbGaLFIO2xOpAWfbR-anm9nY5khiYyZ1y9bL3Q4VqamxsjJ1TkAA9ICA81DwbDkFes28SzzMsIHFZ41CEap5UVYlSTJAAlAMoBAYCyT-Ytcx+P5FmqBk8UbS9VzbACMMWMCIGWRMgA

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions