I want to define a TypeScript class that will receive it's properties via a plain object (like a database document).
class Car {
color: string;
constructor(props: ???) {
Object.assign(this, props)
}
}
What is the best way to type props
?
I could create another interface, called CarProps
and define them there, like:
class Car implements CarProps {
constructor(props: CarProps) {
Object.assign(this, props)
}
}
I am struggling with what to name the interface however, since the TypeScript Handbook forbids starting interface names with "I" (e.g. ICar). Since I would end up with an interface and class that define "Car", they both cant have the same name, so one of them has to be offset like "CarProps", "ICar", or "CarClass".
A problem with this approach is that the properties must be defined twice:
interface CarProps {
color: string;
}
class Car implements CarProps {
color: string; // duplication here
}
Some solutions are offered here (interface merging and abstract classes): Why the need to redefine properties when implementing an interface in TypeScript?
Would appreciate any suggestions on the best practice for this approach.