'How to access a dynamic key in Typescript
I have the following code:
type StringMapType<K extends string[]> = Record<K[number], string>
const en = {
'general': {
'hi': {
string: 'Aenean ullamcorper neque id elementum commodo. {{firstName}}',
params: ['firstName']
},
'bye': {
string: 'Aenean ullamcorper neque id elementum commodo.',
params: null
}
},
} as const
const getLocalizedString = <ContextType extends keyof typeof en, KeyType extends keyof typeof en[ContextType], ParamsType extends typeof en[ContextType][KeyType]['params']>(context: ContextType, key: KeyType, ...params: typeof en[ContextType][KeyType]['params'] extends null ? [undefined?] : [StringMapType<ParamsType>]) => {
// Code that would return the correct value
}
getLocalizedString('general', 'hi', {
firstName: 'John'
})
For some reason, I'm getting an error on the ParamsType saying that Type '"params"' cannot be used to index type. The code itself works and does what I want, just wondering if there is any way how to get around this error.
Thanks in advance
Solution
Based on @seti's answer
const en = {
general: {
hi: {
string: 'hi, {{firstName}}',
params: ['firstName'] as const,
},
bye: {
string: 'bye',
params: [] as const,
}
},
} as const
const translations = {
en,
} as const
const language = 'en'
type CT = keyof typeof en
type KT = keyof typeof en[CT]
type ParamsType<KeyType extends KT> = typeof en[CT][KeyType]['params'][number]
type StringType<KeyType extends KT> = typeof en[CT][KeyType]['string']
const getLocalizedString = <ContextType extends CT = CT, KeyType extends KT = KT>(
context: ContextType,
key: KeyType,
...params: ParamsType<KeyType> extends undefined ? [undefined?] : [{ [key in ParamsType<KeyType>]: string }]
): StringType<KeyType> => {
return translations[language][context][key].string
}
getLocalizedString('general', 'hi', {firstName: 'John'})
getLocalizedString('general', 'bye')
Solution 1:[1]
I think maybe rvm just doesnt work properly on m1 yet? Try just using brew install ruby for now. It should work the same.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matthias Lee |
