Strongly type Form lines.
[ustaxlib.git] / src / Form.ts
1 import TaxReturn from './TaxReturn';
2 import { Line } from './Line';
3 import { InconsistencyError, NotFoundError } from './Errors';
4
5 export default abstract class Form<L extends { [key: string]: Line<any> },
6 I = unknown> {
7 abstract readonly name: string;
8
9 protected abstract readonly _lines: L;
10
11 readonly supportsMultipleCopies: boolean = false;
12
13 private readonly _input?: I;
14
15 constructor(input?: I) {
16 this._input = input;
17 }
18
19 getLine<K extends keyof L>(id: K): L[K] {
20 if (!(id in this._lines))
21 throw new NotFoundError(`Form ${this.name} does not have line ${id}`);
22 const line = this._lines[id];
23 // We cannot apply this to every line in the constructor because |_lines|
24 // is abstract, so do it on getLine().
25 line.form = this;
26 return line;
27 }
28
29 getValue<K extends keyof L>(tr: TaxReturn, id: K): ReturnType<L[K]['value']> {
30 const line: L[K] = this.getLine(id);
31 return line.value(tr);
32 }
33
34 getInput<K extends keyof I>(name: K): I[K] {
35 if (!(name in this._input)) {
36 throw new NotFoundError(`No input with key ${name} on form ${this.name}`);
37 }
38 return this._input[name];
39 }
40 };