Wrap the body of a for-in loop in an if statement with a hasOwnProperty guard
129 const obj = {} as Record<keyof TOptions, unknown>;
130 const options = optionsCallback(optionsFactory);
131
132 for (const key in options) {133 obj[key] = {134 ...configuration?.[key],135 ...options[key],136 };137 }138
139 return obj as {
140 [key in keyof TOptions]: TOptions[key] & FieldConfiguration<TOptions>;
Description
Looping over objects with a for in
loop will include properties that are inherited through the prototype chain.
This behavior can lead to unexpected keys in your for loop.
Bad Practice
for (const key in foo) {
doSomething(key);
}
Recommended
for (const key in foo) {
if (Object.prototype.hasOwnProperty.call(foo, key)) {
doSomething(key);
}
}
for (const key of Object.keys(foo)) {
doSomething(key);
}