Home > Software engineering >  Is there a way for typescript to type using broad keys of a defined object in typescript?
Is there a way for typescript to type using broad keys of a defined object in typescript?

Time:09-15

const obj: {[key: string]: string} = {foo: 'x', bar: 'y'};

type ObjType = keyof typeof obj;

Without modifying the type of obj, how can I make ObjType accept only "foo" or "bar" and not any string ?

CodePudding user response:

This can't be done on typescript 4.8. You cannot constrain a type, and get a more specific version of that type to use in the same assignment.

The typical workaround is to use a generic function, which sort of sucks.

function makeObj<T extends { [key: string]: string }>(obj: T) {
    return obj
}

const obj = makeObj({foo: 'x', bar: 'y'})

type ObjType = keyof typeof obj // 'foo' | 'bar'

See playground


However, the next version of typescript (4.9) seems likely to contain the satisfies operator. See this github issue

This will let you apply a constraint, and infer the more specific type all at once.

const obj = {foo: 'x', bar: 'y'} satisfies { [key: string]: string }

type ObjType = keyof typeof obj // 'foo' | 'bar'

See playground


But either way, you will have to modify how obj is declared to make any of this work.

CodePudding user response:

Just let the inference do the job :

const obj = {foo: 'x', bar: 'y'};

type ObjType = keyof typeof obj; //  "foo" | "bar" 
  • Related