Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Key Inferences for TypeScript Objects

// 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.

  1. When writing the inside of obj, get help from the value of the record type.
  2. 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading