2024-05-08.md

🏑

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

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


문제

  • κ°œλ… ν€΄μ¦ˆ
    • ꡐ재의 κ°œλ…μ„ κΈ°μ€€μœΌλ‘œ O/X, λ˜λŠ” n지선닀 ν€΄μ¦ˆ
  • λ³€ν˜• 예제
    • ꡐ재의 예제λ₯Ό μ°Έκ³ ν•˜μ—¬ λ³€ν˜•ν•œ 예제λ₯Ό λ§Œλ“ λ‹€.
  • λΈ”λž™λ°•μŠ€ ν€΄μ¦ˆ
    • ν…ŒμŠ€νŠΈ μΌ€μ΄μŠ€κ°€ μ‹€νŒ¨ν•œ 원인을 μ°ΎλŠ”λ‹€.

μ•„μ΄ν…œ 2

Example

  • λ‹€μŒ μ½”λ“œμ—μ„œ μ—λŸ¬κ°€ λ°œμƒν•˜λŠ” μœ„μΉ˜μ™€ 이유 (1개 이상)?
  • μ—λŸ¬μ™€ κ΄€λ ¨λœ tsconfig μ†μ„±μ˜ 이름은?
    1. noImplicitThis
    2. noImplicitAny
    3. noImplicitReturns
    4. strictNullChecks
  • μ—λŸ¬ ν•΄κ²° 방법은?
// tsConfig: {"noImplicitAny":true,"strictNullChecks":true}

function registerCallback(callback) {
  callback();

  if (callback) {
    callback();
  } else {
    console.log("No callback provided.");
  }
}

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

registerCallback(() => {
  button.addEventListener("click", (e) => {
    e.stopPropagation();
    console.log("Button clicked!");
  });
});

μ•„μ΄ν…œ 3

  • λŸ°νƒ€μž„μ— λ™μ μœΌλ‘œ νƒ€μž…μ„ νŒλ³„ν•˜λŠ” ν•¨μˆ˜ μž‘μ„±
    • A: 속성 체크
    • B: Tagged Union
interface Circle {
  kind: "circle";
  radius: number;
}

interface Square {
  kind: "square";
  width: number;

type Shape = Circle | Square;

// Circle일 λ•ŒλŠ” Math.PI * shape.radius ** 2을 λ°˜ν™˜
// Square일 λ•ŒλŠ” shape.width ** 2λ₯Ό λ°˜ν™˜
function calculateArea(shape: Shape) {
  πŸ€”
}

// ν…ŒμŠ€νŠΈ
const circle: Circle = { kind: "circle", radius: 5 };
const square: Square = { kind: "square", width: 4 };

console.log(calculateArea(circle)); // 78.54...
console.log(calculateArea(square)); // 16
  • C: νƒ€μž…μ„ 클래슀둜 λ§Œλ“€κΈ°
class Circle {
  constructor(public radius: number) {}
}

class Square {
  constructor(public width: number) {}
}

type Shape = Circle | Square;

// Circle일 λ•ŒλŠ” Math.PI * shape.radius ** 2을 λ°˜ν™˜
// Square일 λ•ŒλŠ” shape.width ** 2λ₯Ό λ°˜ν™˜
function calculateArea(shape: Shape) {
  if (shape instanceof Circle) {
    return Math.PI * shape.radius ** 2;
  } else if (shape instanceof Square) {
    return shape.width ** 2;
  }
}

// ν…ŒμŠ€νŠΈ
const circle = new Circle(5);
const square = new Square(4);

console.log(calculateArea(circle)); // 78.54...
console.log(calculateArea(square)); // 16