interface MyInterface {
prop1: string;
prop2: number;
// other properties
}
const myObject: MyInterface = {
prop1: "value1",
prop2: 123,
// other properties
};
console.log("method 1: iterate over entries")
for (const [key, value] of Object.entries(myObject)) {
console.log(key, value);
}
console.log("method 2: iterate over keys")
for (const key of Object.keys(myObject) as Array<keyof MyInterface>) {
const value = myObject[key]; // Now TypeScript knows key is a keyof MyInterface
console.log(key, value);
}
Created
November 23, 2023 16:13
-
-
Save rshaker/ff626ae4c223c389c5d6ea6c246dc7e5 to your computer and use it in GitHub Desktop.
Iterating over Interface properties in Typescript
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment