// A
export const config: Record<string, number> = {
a: 1,
b: 2,
} as const
export const test = (configKey: keyof typeof config) => {
console.log(configKey)
}
test('') // key not deduced
// B
type A = 'a' | 'b'
export const config: Record<A, number> = {
a: 1,
b: 2,
} as const
export const test = (configKey: keyof typeof config) => {
console.log(configKey)
}
test('') //Key inference ok
My obj has a type.
The current value is number for example, but in reality
It’s more complicated.
For A, key inference is not possible when you want to use a function that receives only obj’s key.
Of course, B works well.
However, I have no choice but to use A’s method considering the following.
- When writing the inside of obj, get help from the value of the record type.
- When fixing the inside of obj, it should not be fixed anywhere else.(Key must be fixed for b)
Therefore, I have to use A’s obj.
But in this case, I want to know how to infer the key of A’s obj.
>Solution :
When you add a type annotation to the config it ignores your const assertion, thus you need to remove the type, but in that case, the type-checking doesn’t work.
Fortunately, the satisfies operator, which was introduced in the typescript 4.9 assures the type safety:
export const config = {
a: 1,
b: 2,
} as const satisfies Record<string, number>;
Testing:
test(''); // error
test('a'); // no error
test('b'); // no error