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 μμ±μ μ΄λ¦μ?
- noImplicitThis
- noImplicitAny
- noImplicitReturns
- 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