5

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>

2
  • Does this answer help stackoverflow.com/a/65020179/4155700 ? Commented Sep 3, 2021 at 12:44
  • Unfortunately no. That's why I wrote that I know how to use string manipulation types to convert but not to test. Commented Sep 3, 2021 at 18:21

1 Answer 1

4
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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
If you don\t know all keys - unfortunatelly you should use extra function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.