From b51c88b40714d3b7183fd593c9e4496ff5dc7162 Mon Sep 17 00:00:00 2001 From: Robert Sesek Date: Tue, 18 Feb 2020 20:32:53 -0500 Subject: [PATCH] Make Form input strongly typed with generics. --- src/Form.test.ts | 12 ++++++++---- src/Form.ts | 10 +++++----- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/Form.test.ts b/src/Form.test.ts index 795fd85..b7c3d0e 100644 --- a/src/Form.test.ts +++ b/src/Form.test.ts @@ -71,12 +71,16 @@ test('add line to two forms', () => { }); test('input', () => { - class TestForm extends Form { + interface TestInput { + filingStatus: string; + money: number; + }; + class TestForm extends Form { get name() { return '1040'; } protected getLines() { return []; } }; - const f = new TestForm({ 'Filing Status': 'S' }); - expect(f.getInput('Filing Status')).toBe('S'); - expect(() => f.getInput('Unknown')).toThrow(NotFoundError); + + const f = new TestForm({ filingStatus: 'S', money: 100.0 }); + expect(f.getInput('filingStatus')).toBe('S'); }); diff --git a/src/Form.ts b/src/Form.ts index e638294..507a611 100644 --- a/src/Form.ts +++ b/src/Form.ts @@ -1,13 +1,13 @@ import { Line } from './Line'; import { InconsistencyError, NotFoundError } from './Errors'; -export default abstract class Form { +export default abstract class Form { private _lines: Line[] = []; - private _input?: object; + private _input?: I; abstract get name(): string; - constructor(input?: object) { + constructor(input?: I) { this._input = input; this.getLines().map(this.addLine.bind(this)); } @@ -40,10 +40,10 @@ export default abstract class Form { return lines[0]; } - getInput(name: string): T { + getInput(name: K): I[K] { if (!(name in this._input)) { throw new NotFoundError(`No input with key ${name} on form ${this.name}`); } - return this._input[name] as T; + return this._input[name]; } }; -- 2.22.5