0

I have the object x with the type [key in string]: any. I want to get key of type of x but when I do keyof typeof x, it's string. How can I get the keys of x?

My code. InbuiltRuleNames is string.

export type InbuiltRuleNames = keyof typeof rules;

// OBS: DONT CHANGE PREFIX!!!
// OBS: ADD ISSUE TO ISSUEIDS.md
export const rules: { readonly [name in string]: Rule } = {
    'multiple-context-bindings': {
        code: prefix(1),
        message: 'Only one of [$0], can control descendant bindings. Separate into distinct elements.'
    },
    'no-viewmodel-reference': {
        code: prefix(2),
        message: 'Missing ViewModel reference in file $0'
    },
    'multiple-comment-bindings': {
        code: prefix(3),
        message: 'Can not have multiple bindings in the same comment.'
    },
    'javascript-syntax-error': {
        code: prefix(4),
        message: 'JavaScript syntax error.'
    }
};
tscpp
  • 1,298
  • 2
  • 12
  • 35
  • 1
    I don't think there's an easy way to infer an object's keys but restrict its values. See [How to make Typescript infer the keys of an object but define type of its value?](https://stackoverflow.com/a/54598743/732284) for a workaround. – rid Jun 07 '20 at 10:13
  • Do I understand you correctly, that you want to have the `type InbuiltRuleNames = "multiple-context-bindings" | "no-viewmodel-reference" | "multiple-comment-bindings" | "javascript-syntax-error"`? The easiest way to to that would be to avoid setting a type to the rules object. Even though it's nicer to have a type. – Paul Jun 07 '20 at 10:35

0 Answers0