2024-05-11.md

🏑

DIL: μ΄νŽ™ν‹°λΈŒ νƒ€μž…μŠ€ν¬λ¦½νŠΈ

μŠ€ν„°λ””: μ›”κ°„ CS, https://github.com/monthly-cs/2024-05-effective-typescript
μž‘μ„±μΌ: 2024-05-11
μž‘μ„±μž: dusunax


PPT μ½”λ“œ 정리

function registerCallback(callback: () => void) {
  if (callback) {
    callback();
  } else {
    console.log("No callback provided.");
  }
}

const button = document.getElementById("myButton");

registerCallback(() => {
  button &&
    button.addEventListener("click", (e) => {
      e.stopPropagation();
      console.log("Button clicked!");
    });
});
/**
 * - 였λ₯˜κ°€ λ°œμƒν• κΉŒμš”?
 * - μ–΄λ–€ μœ„μΉ˜μ—μ„œ λ°œμƒν• κΉŒμš”?
 * - μ΄μœ λŠ” λ¬΄μ—‡μΈκ°€μš”?
 * */
// 경우 A
function λ‘˜_λ‚˜λˆ„κΈ°_A(input) {
  return input / 2;
}
console.log(λ‘˜_λ‚˜λˆ„κΈ°_A("10"));

// 경우 B
function λ‘˜_λ‚˜λˆ„κΈ°_B(input: number) {
  return input / 2;
}
console.log(λ‘˜_λ‚˜λˆ„κΈ°_B("10"));

// 경우 C
function λ‘˜_λ‚˜λˆ„κΈ°_C(input: number) {
  return input / 2;
}
console.log(λ‘˜_λ‚˜λˆ„κΈ°_C("10" as any));
function calculateArea(shape: Shape): number {
  if (shape.kind === "circle") {
    return Math.PI * shape.radius ** 2;
  } else if (shape.kind === "square") {
    return shape.width ** 2;
  } else {
    throw new Error("Unknown shape kind");
  }
}

function calculateArea(shape: Shape): number {
  if ("radius" in shape) {
    return Math.PI * shape.radius ** 2;
  } else if ("width" in shape) {
    return shape.width ** 2;
  } else {
    throw new Error("Unknown shape kind");
  }
}
function format(input: number): string; // 숫자 ν˜•μ‹
function format(input: string): string; // λ¬Έμžμ—΄ ν˜•μ‹

function format(input: any): string {
  if (typeof input === "number") {
    return `Number: ${input}`;
  } else if (typeof input === "string") {
    return `String: ${input}`;
  } else {
    throw new Error("Unsupported type");
  }
}

const formattedNumber = format(42); // "Number: 42"
const formattedString = format("Hello"); // "String: Hello"
console.log(formattedNumber, formattedString);

any: λ¬Έμ œμ•Ό 문제

interface UserData {
  id: string;
  name: string;
  height: string;
}

interface DataProvider {
  fetchData: (userId: string) => any;
}

class UserApi implements DataProvider {
  private data: any;

  constructor() {
    this.data = {};
  }

  setData(data: UserData) {
    this.data = data;
  }

  fetchData(userId: string) {
    // λ„€νŠΈμ›Œν¬ μš”μ²­~
    // μ‹€μ œ μ‹œλ‚˜λ¦¬μ˜€μ—μ„œλŠ” μ‚¬μš©μž IDλ₯Ό 기반으둜 APIμ—μ„œ μ‚¬μš©μž 데이터λ₯Ό κ°€μ Έμ˜¬ 것
    return {
      id: userId,
      name: "κΉ€μœ μ €",
      height: "180.5",
    };
  }
}

const userApi: DataProvider = new UserApi();
const fetchedUserData = userApi.fetchData("μœ μ €μ•„μ΄λ””");
console.log(`User Height: ${fetchedUserData.height.toFixed(2)}`);
// 🚫 λŸ°νƒ€μž„ 였λ₯˜: toFixedλŠ” ν•¨μˆ˜κ°€ μ•„λ‹˜

any: μ œλ„€λ¦­

interface UserData {
  id: string;
  name: string;
  height: string;
}

interface DataProvider<T> {
  fetchData: (userId: string) => T;
}

class UserApi implements DataProvider<UserData> {
  private data: UserData | undefined;

  constructor() {
    this.data = undefined;
  }

  setData(data: UserData) {
    this.data = data;
  }

  fetchData(userId: string) {
    // λ„€νŠΈμ›Œν¬ μš”μ²­~
    // μ‹€μ œ μ‹œλ‚˜λ¦¬μ˜€μ—μ„œλŠ” μ‚¬μš©μž IDλ₯Ό 기반으둜 APIμ—μ„œ λΉ„λ™κΈ°λ‘œ μ‚¬μš©μž 데이터λ₯Ό κ°€μ Έμ˜¬ 것
    return {
      id: userId,
      name: "κΉ€μœ μ €",
      height: "180.5",
    };
  }
}

const userApi = new UserApi();
const fetchedUserData = userApi.fetchData("μœ μ €μ•„μ΄λ””");
console.log(`User Height: ${fetchedUserData.height.toFixed(2)}`);
// 🚫 λŸ°νƒ€μž„ 였λ₯˜: toFixedλŠ” ν•¨μˆ˜κ°€ μ•„λ‹˜
/ ν™˜μœ¨ 정보λ₯Ό ν‘œν˜„ν•˜λŠ” μΈν„°νŽ˜μ΄μŠ€
interface ExchangeRate {
  currency: string;
  rate: number;
}

// λ‹¬λŸ¬λ₯Ό μ›ν™”λ‘œ ν™˜μ „ν•˜λŠ” ν•¨μˆ˜
const exchangeDollarToWon: (amount: number, exchangeRate: ExchangeRate) => number =
  (amount: number, exchangeRate: ExchangeRate): number => {
    if (typeof amount !== 'number' || typeof exchangeRate.rate !== 'number') {
      // μˆ«μžκ°€ μ•„λ‹Œ μΈμžκ°€ μ „λ‹¬λ˜λ©΄ 였λ₯˜ λ°œμƒ
      throw new Error('Invalid input: arguments must be numbers');
    }
    return amount * exchangeRate.rate;
};

// λ‹¬λŸ¬λ₯Ό 유둜둜 ν™˜μ „ν•˜λŠ” ν•¨μˆ˜
const exchangeDollarToEuro: any = (amount: number, exchangeRate: ExchangeRate): number => {
  return amount * exchangeRate.rate;
};

// ν™˜μ „ 정보
const dollarToWonRate: ExchangeRate = { currency: 'KRW', rate: 1150 };
const dollarToEuroRate: ExchangeRate = { currency: 'EUR', rate: 0.85 };

// ν™˜μ „ ν•¨μˆ˜ 호좜
console.log(exchangeDollarToWon(100, dollarToWonRate)); // 115000
console.log(exchangeDollarToEuro(100, dollarToEuroRate)); // 85
console.log(exchangeDollarToEuro("100", dollarToEuroRate)); // "100" λ¬Έμžμ—΄μ΄ λ°˜ν™˜λ¨