I have some issues with TypeScript. I'm trying to transform some value that is coming from parent component to child. Parent is sending value that can be EN, FR or NL, and those values I should transform to numbers, so I did that:
const transform_translation = {
'EN': 1,
'FR': 2,
'NL': 3
};
But when I try to get value like transform_translation[props.language]
, It says;
S7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ EN: number; FR: number; NL:
Props:
props: {
language: {
type: String,
default: ['EN', 'NL', 'FR'],
required: true
},
.
.
.
}
How should I define them then? I work first time with TS btw.
number; }'.
CodePudding user response:
You should tell ts what you're passing is not just string but limited to the available keys of the languages you have:
const transform_translation = {
EN: 1,
FR: 2,
NL: 3
};
// create type out of valid keys of object
type Language = keyof typeof transform_translation;
const getLanguageNum = (lang: Language) => transform_translation[lang];
console.log(getLanguageNum("EN")); // 1
CodePudding user response:
I would either create an enum or type for the key like so. Then when accessing it you can cast the the key into the type as follows
type ITransformTranslationKey = 'EN' | 'FR' | 'NL';
const transform_translation: Record<ITransformTranslationKey, number> = {
'EN': 1,
'FR': 2,
'NL': 3
};
const someVar: ITransformTranslationKey = 'E' 'N'; // you can define the type here
transform_translation[someVar as ITransformTranslationKey] // or here