Struggling with the compiler here and wondering if I'm on the wrong track or just pursuing a misguided approach.
My goal is to have a class with required parameters, along with an input interface
containing optional parameters. If a parameter is missing from the Input
, the class constructor should default to a sensible value.
interface PersonInput {
name?: string;
age?: number;
}
class Person {
name: string;
age: number;
constructor(input: PersonInput) {
this.name = "Zach";
this.age = 30;
for (const key in input) {
this[key] = input[key]; // <--- Running into errors here
}
}
}
// Error: TS7053: Element implicitly has an 'any' type because
// expression of type 'string' can't be used to index type 'PersonInput'.
If I ensure that the element doesn't have an any
type associated with it:
\\ ...snip
for (const key in input) {
const personParam: keyof Person = key; // <-- Type 'string | number | undefined' is not assignable to type 'never'
this[personParam] = input[personParam];
}
\\...snip
To work around this, I opted not to spread properties and instead did something like this:
//...snip
class Person {
name: string;
age: number;
constructor(input: PersonInput) {
this.name = input.name || "Zach";
this.age = input.age || 30;
}
}
What am I missing?
Addendum
I've come across the param!
syntax - is that relevant in this case? I don't think so since the loop only executes if the parameter has been defined, rather than relying on a property being passed in the input
.