The following code fails as TypeScript:
const exampleFn = function<AttributeName extends 'attributeA' | 'attributeB'>(
whatToProcess: AttributeName extends 'attributeA' ? {attributeA: string} : {attributeB: string},
attributeName: AttributeName
) {
//Error here: Type 'AttributeName' cannot be used to index type
//'AttributeName extends "attributeA" ? { attributeA: string; } : { attributeB: string; }'.ts(2536)
console.log(whatToProcess[attributeName]);
}
Playground link here.
When attributeName is 'attributeA', whatToProcess should have attributeA, and when attributeName is 'attributeB', whatToProcess should have attributeB, so in each case attributeName should be usable to index the type of whatToProcess.
It seems I'm not understanding something about how the generic + conditional typing system works in TypeScript; if someone can help me figure out how this is supposed to be done that'd be much appreciated!