Skip to content

Instantly share code, notes, and snippets.

@rshaker
Created November 23, 2023 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rshaker/ff626ae4c223c389c5d6ea6c246dc7e5 to your computer and use it in GitHub Desktop.
Save rshaker/ff626ae4c223c389c5d6ea6c246dc7e5 to your computer and use it in GitHub Desktop.
Iterating over Interface properties in Typescript
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);
}

Playground Link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment