benjamin.keen
benjamin.keen

Reputation: 1984

Declare Typescript type for arbitrary object properties

Haven't stumbled upon the right TS syntax for this with Typescript 3.7.3.

I have an arbitrary object, like:

var obj = {
    one: ...,
    two: ...
    three: ...
};

I need to generate a type of all keys from that object, creating a type like so:

type ObjKeys = 'one' | 'two' | 'three';

I'd read somewhere that this syntax should work, but perhaps that was with older versions of TS.

type ObjKeys = keyof typeof obj;

Any idea?

Upvotes: 2

Views: 436

Answers (1)

benjamin.keen
benjamin.keen

Reputation: 1984

jcalz was quite right in the comment above: the syntax was correct. In my case the problem was with my build - I was using babel-eslint as the parser, but was extending "plugin:@typescript-eslint/recommended"). Switching to @typescript-eslint as the parser fixed it.

.eslintrc

{
    "parser": "@typescript-eslint/parser",
    ...
}

Upvotes: 2

Related Questions