In the process of creating a function called getLocale(obj, key, locale)
, I aim to retrieve a specific locale from an object based on a given key. If the desired locale variant is not available, it should return a fallback option.
While adding type checking to this function, I encountered a challenge in merging the key
and locale
arguments to effectively create the keyof obj
:
Here's my data:
const data = {
name_nl: 'Naam',
name_en: 'Name',
}
The function looks like this:
const allowedLangs = ['nl', 'en'] as const;
function getLocale<T extends Record<K, any>, K extends keyof any>(
data: T,
key: K,
locale: typeof allowedLangs[number]
): T[K] | 'not-found' {
return data[`${key}_${locale}`] || data[`${key}_en`] || 'not-found';
}
When calling the function:
getLocale(data, 'name', 'nl'); // Naam
However, TypeScript raises an error stating that
Property 'name' is missing in type
. This is because K
does not directly represent a keyof T</code in the function; rather, it's a combination of <code>locale
and key
.
Is there a solution to merge these arguments seamlessly?