I'm trying to create a lookup where each key determines the type of the corresponding value.
Consider this code:
type Language = 'en' | 'de';
// Language-specific parser
type Parser<TLanguage extends Language> = (text: string, language: TLanguage) => any;
// Lookup that contains a typed parser for each language
const parsers: { [language in Language]: Parser<language> } = {
'de': () => null, // Dummy values
'en': () => null,
};
The idea is that for each Language, parsers contains a language-specific parser strongly typed for that particular language.
This assignment works as expected:
const englishParser: Parser<'en'> = parsers.en;
But this assignment doesn't work, and I can't figure out why. My goal is to write type-safe code without type assertions.
function test<TLanguage extends Language>(language: TLanguage) {
// Error:
// Type '{ en: Parser<"en">; de: Parser<"de">; }[TLanguage]' is not assignable
// to type 'Parser<TLanguage>'.
const parser: Parser<TLanguage> = parsers[language]; //
}
Here's a TypeScript Playground link that demonstrates the problem.