4

Is there a way to contruct a type that will allow any kind of keys for object as long as they are UPPERCASE?

I want this to pass:

const example: OnlyUppercaseKeys = {
  TEST: 'any string',
  TEST_ME: 'any string'
};

and I want this to fail:

const example: OnlyUppercaseKeys = {
  Test: 'any string',
  'test_me': 'any string'
};

I know there are string manipulation types. I can even use them to construct a type that will convert any keys to uppercase, but I don't know how to write type with a test that would check it in Record<???, string>

Buszmen
  • 1,978
  • 18
  • 25

1 Answers1

3
const example: Record<Capitalize<string>, unknown> = {
    TEST: 'any string',
    TEST_ME: 'any string',
    a: 'a'
}; // don't work

It is possible to do it with standalone type if you know all of your keys upfront.

type AllowedKeys = 'a' | 'b'

const example2: Record<Uppercase<AllowedKeys>, unknown> = {
    A: 'a',
    B: 'b'
}

In order to do this, you should use an extra function.

const uppercaseed = <
    Keys extends string,
    Obj extends Record<Keys, unknown>
>(obj: Obj & Record<Uppercase<keyof Obj & string>, unknown>) => obj

uppercaseed({ AA: 1 }) // ok
uppercaseed({ Aa: 1 }) // error
uppercaseed({ aa: 1 }) // error

Please take a look at this question. It almost the same, you just need to replace Lowercase with Upercase

Londeren
  • 3,202
  • 25
  • 26
  • Interesting take. This method function does static type checking, but it's a little unhandy. Unfortunately I don't know all keys. The object will be expanded with more keys in the future. However, you are right that the question you linked is almost the same think I asked. – Buszmen Sep 03 '21 at 09:45
  • 1
    If you don\t know all keys - unfortunatelly you should use extra function – captain-yossarian from Ukraine Sep 03 '21 at 09:53