I'm getting into classes and interfaces. And I got one thing about it that annoys me, this is the first time I work with these kind of things so bear with me here..
Let's say I got this interface:
// IFoo.d.ts
export default interface IFoo {
foo: string;
bar: number;
}
When I implement it in a class I do the following:
// FooModel.ts
import IFoo from './IFoo';
export default class FooModel implements IFoo {
foo: string;
bar: number;
constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
this.foo = foo;
}
}
Why do I have to implement the same properties all over again?
This is basically the same as copy-paste but with a strict convention. Also, I have to type foo
and bar
a total of 6 times each to get it properly assigned with default optional values, based on an interface.
Is there a more efficient way to do this too?
Edit; I'm trying to achieve the following:
A class with the properties, from which the properties can be used for typescript's checking, like this: interface
export default interface FooDTO {
foo: string;
bar: number;
}
model
export interface IFoo {
foo: string;
bar: number;
}
export default class FooModel implements IFoo {
foo: string;
bar: number;
constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
this.foo = foo;
}
}
controller
export default class FooController {
public static async readAll(): Array<FooDTO> {
// some model stuff which maps query to dto
return Array<FooDTO>result;
}
}