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'
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'
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"