How to get keys type as array from interface?
See the question that Jared mentioned.
If control over the order of the keys matters in the array, it is better to define the array and derive the shape of your interface from the array:
TS Playground
const exampleKeys = ['foo', 'bar'] as const;
type ExampleKeys = typeof exampleKeys; // the type you want
type ExampleKey = ExampleKeys[number];
type Example = Record<ExampleKey, boolean>;
const example: Example = {
foo: true,
bar: false,
};
Using this technique also solves a frequent problem: iterating objects in a type-safe way:
for (const key in example) {
const bool = example[key]; /*
^^^^^^^^^^^^
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Example'.
No index signature with a parameter of type 'string' was found on type 'Example'.(7053) */
}
for (const key of exampleKeys) {
const bool = example[key];
}
Interface keys from array in TypeScript
You can use the keyof
operator for exactly this purpose.
interface MyInterface {
key1: boolean;
key2: boolean;
}
const myObj: MyInterface = {
key1: true,
key2: false,
}
const myArray: Array<keyof MyInterface> = ['key1', 'key2'];
// or ...
const myOtherArray: Array<keyof typeof myObj> = ['key1', 'key2'];
You could also go backwards like so
const myArray = ['key1', 'key2'] as const;
type MyType = Record<typeof myArray[number], boolean>;
const myObj: MyType = {
key1: true,
key2: false,
}
Related Topics
"You May Need an Appropriate Loader to Handle This File Type" with Webpack and Babel
How to Addeventlistener to Multiple Elements in a Single Line
Http Head Request in JavaScript/Ajax
Trying to Validate Url Using JavaScript
Why How to Access Typescript Private Members When I Shouldn't Be Able To
Passing Arguments Forward to Another JavaScript Function
How to Cache an Image in JavaScript
Why Do We Need to Use Radix Parameter When Calling Parseint
JavaScript Regexp + Word Boundaries + Unicode Characters
Official Information on 'Arguments' in Es6 Arrow Functions
Find Dom Element by Id When Id Contains Square Brackets
Meteor.Publish: Publish Collection Which Depends on Other Collection
How to Destructure All Properties into the Current Scope/Closure in Es2015
Uncaught Syntaxerror: Unexpected Token :