Let's say I have an array of valid key names
const validKeys = ['a', 'b', 'c']
How can I create an object type that accepts only these keys? This doesn't work:
interface MyObject {
[key in validKeys]: number // for example
}
You can use const assertion (added in typescript 3.4) in order to preserve literal types of array items:
const validKeys = ['a', 'b', 'c'] as const;
type Keys = (typeof validKeys)[number]; // "a" | "b" | "c"
type MyObject = { [key in Keys]: number } // { a: number; b: number; c: number; }
If you use an older typescript version (>=3.0), you can add small utility function which will convert parameters to tuple of literals:
const tuple = <T extends string[]>(...args: T): T => args;
const validKeys = tuple('a', 'b', 'c'); // ["a", "b", "c"]
if your validKeys are static you can create a type for it. And then from that type, you can set type for object keys.
You can do something like:
type ValidKeys = 'a' | 'b' | 'c'
type MyObject = {
[key in ValidKeys]?: number //You can remove ? if all the keys are mandatory
}
const validKeys: ValidKeys[] = ['a', 'b', 'c']
const obj: MyObject = {
a: 1,
b: 1,
c: 1
}
The keys of object
objcan only be one of ValidKeys.
myObject['a']myObj.ainterface MyObject { a: number; b: number; c: number }if the keys are optional `interface MyObject { a?: number; b?: number; c?: number } .