Tuple 예제

旅人·2023년 4월 26일
0

HasFormatter.ts

export interface HasFormatter {
  format(): string;
}

invoice.ts

import { HasFormatter } from "../interfaces/HasFormatter.js";

// classes
export class Invoice implements HasFormatter {
  constructor(
    readonly client: string,
    private details: string,
    public amount: number
  ) {}

  format() {
    return `${this.client} owes ${this.amount} pounds for ${this.details}`;
  }
}

payment.ts

import { HasFormatter } from "../interfaces/HasFormatter.js";

// classes
export class Payment implements HasFormatter {
  constructor(
    readonly recipient: string,
    private details: string,
    public amount: number
  ) {}

  format() {
    return `${this.recipient} is owed ${this.amount} pounds for ${this.details}`;
  }
}

ListTemplate.ts

import { HasFormatter } from "../interfaces/HasFormatter.js";

export class ListTemplate {
  constructor(private container: HTMLUListElement) {}

  render(item: HasFormatter, heading: string, pos: "start" | "end") {
    const li = document.createElement("li");

    const h4 = document.createElement("h4");
    h4.innerText = heading;
    li.append(h4);

    const p = document.createElement("p");
    p.innerText = item.format();
    li.append(p);

    if (pos === "start") {
      this.container.prepend(li);
    } else {
      this.container.append(li);
    }
  }
}

/*
    1. register a list container (ul) in the constructor
    2. create a render method to render a row 'li' to the container
        -- accepts arguments: invoice or payment, a heading, a position
        -- create the html template(li, h4, p)
        -- add the 'li' template to the start/end of the list
*/

튜플과 spread 연산자를 통해 간편하게 객체를 생성할 수 있음


(생략)....  


form.addEventListener("submit", (e: Event) => {
  e.preventDefault();

  let values: [string, string, number];
  values = [tofrom.value, details.value, amount.valueAsNumber];

  let doc: HasFormatter;
  if (type.value === "invoice") {
    doc = new Invoice(...values);
  } else {
    doc = new Payment(...values);
  }

  list.render(doc, type.value, "end");
});

참고

https://www.youtube.com/watch?v=tHSstkiVbc8&list=PL4cUxeGkcC9gUgr39Q_yD6v-bSyMwKPUI&index=20

profile
一期一会

0개의 댓글