[Typescript] Iterating Over Object Keys in Typescript
import { expect, it, vitest } from 'vitest';
interface User {
id: number;
name: string;
}
function printUser(user: User) {
Object.keys(user).forEach((key) => {
// @ts-expect-error
console.log(user[key]);
});
}
it('Should log all the keys of the user', () => {
const consoleSpy = vitest.spyOn(console, 'log');
printUser({
id: 1,
name: 'Waqas',
});
expect(consoleSpy).toHaveBeenCalledWith(1);
expect(consoleSpy).toHaveBeenCalledWith('Waqas');
});
After Object.keys
, the key
is string
type, therefore when we do user[key]
, Typescript complians.
Two way to resolve the issues
1. Widen the restriction
function printObjectValue(obj: Record<string, any>) {
Object.keys(obj).forEach((key) => {
console.log(obj[key]);
});
}
Using a generic function to print object value.
2. Using as
function printUser(user: User) {
Object.keys(user).forEach((key) => {
console.log(user[key as keyof User]);
});
}