2024-06-05.md
π‘DIL: μ΄νν°λΈ νμ μ€ν¬λ¦½νΈ
μ€ν°λ: μκ° CS, https://github.com/monthly-cs/2024-05-effective-typescript
μμ±μΌ: 2024-06-05
μμ±μ: dusunax
μμ΄ν 41: anyμ μ§νλ₯Ό μ΄ν΄νκΈ° Understand Evolving Types
- μΌλ°μ μΈ νμ : λ³μμ νμ μ λ³μλ₯Ό μ μΈν λ κ²°μ > μ΄ν μ 체
- any: μ΄λΈμ΄
function range(start: number, limit: number) {
const nums = [];
// ^? const nums: any[]
for (let i = start; i < limit; i++) {
nums.push(i);
// ^? const nums: any[]
}
return nums;
// ^? const nums: number[]
// number κ°μ λ£λ μκ° μ§ννλ€
}
- νμ μ’νκΈ° type narrowing μ λ€λ₯Έ μ => λ°°μ΄μ λ€μν νμ μ μμλ₯Ό λ£μΌλ©΄ νμ μ΄ νμ₯λλ©° μ§ννλ€
const result = [];
// ^? const result: any[]
result.push("a");
result;
// ^? const result: string[]
result.push(1);
result;
// ^? const result: (string | number)[]
- μ΄κΈ°κ°μ΄ nullμΈ κ²½μ°λ any μ§ν. try/catch λΈλ‘ μμμ λ³μλ₯Ό ν λΉνλ κ²½μ°μ λ³΄ν΅ λνλ¨
let value = null;
// ^? let value: any
try {
value = doSomethingRiskyAndReturnANumber();
value;
// ^? let value: number
} catch (e) {
console.warn("alas!");
}
value;
// ^? let value: number | null
// μ§ν
- if elseλ¬Έμ κ²½μ°
let value;
// ^? let value: any
if (Math.random() < 0.5) {
value = /hello/;
value;
// ^? let value: RegExp
} else {
value = 12;
value;
// ^? let value: number
}
value;
// ^? let value: number | RegExp
// μ§νν¨
νΉμ§
- any νμ μ§νλ κ° μμμ anyμμ μ μ©λλ©°, λͺ μμ anyλ μ μ§λλ€.
- κ°μ ν λΉνκ±°λ, λ°°μ΄μ μμλ₯Ό λ£μ νμλ§ μΌμ΄λκΈ° λλ¬Έμ => νΈμ§κΈ°μμ μ΄μνκ² λ³΄μΌ μ μλ€. (ν λΉμ΄ μΌμ΄λ μ€μ νμ μ μ‘°μ¬ν΄λ any. ν λΉμ΄ λλ ν, μ§ν)
- μ΄λ ν ν λΉλ νμ§ μκ³ μ¬μ©νλ©΄ noImplicitAny μ€λ₯
- μμμ any μνμΌ λ κ°μ μ½μΌλ € νλ©΄ μ€λ₯κ° λ°μνλ€.
ν¨μ νΈμΆμ κ±°μ³λ μ§ννμ§ μλλ€
- μλ μμμμ .forEach ν¨μ νΈμΆμ κ±°μ³€μ λ μ§ννμ§ μμ
- forEachλ‘ μννλ λμ , λ°°μ΄μ mapκ³Ό filter λ©μλλ‘ λ¨μΌ ꡬ문μΌλ‘ λ°°μ΄ μμ± => any μ 체λ₯Ό μ§νμν€λ λ°©λ² μκ°
function makeSquares(start: number, limit: number) {
const nums = [];
// ~~~~ Variable 'nums' implicitly has type 'any[]' in some locations
range(start, limit).forEach((i) => {
nums.push(i * i); // μ§ννμ§ μλλ€
});
return nums;
// ~~~~ Variable 'nums' implicitly has an 'any[]' type
}
μ§ν λ°©μ?
- μΌλ°μ μΈ λ³μκ° μΆλ‘ λλ μ리μ λμΌνλ€.
- μ§νν λ°°μ΄μ νμ μ΄ (string|number)[]μΌ λ, number[]μ΄μ΄μΌ νλ λ° stringμ΄ μμμ¬μ μ§ννμ κ°λ₯μ±λ μλ€.
- λ°λΌμ λͺ μμ νμ κ΅¬λ¬Έμ΄ λ μμ μ± μλ μ’μ μ€κ³
Things to Remember
- While TypeScript types typically only refine, the types of values initialized to null, undefined, or [] are allowed to evolve.
- μΌλ°μ μΌλ‘ νμ μ μ μ λ§ λμ§λ§, μμμ AnyμΈ κ²½μ° (null, undefined, []λ‘ μ΄κΈ°νλ κ²½μ°) μ§ννλ€
- Recognize and understand this construct where it occurs, and use it to reduce the need for type annotations in your own code.
- μ΄λ° λμμ΄ μΌμ΄λ¨μ μκ³ μμΌλ©΄, νμν κ²½μ° νμ ꡬ문μ μ€μΌ μ μλ€.
- For better error checking, consider providing an explicit type annotation instead of using evolving types.
- μλ¬ μ²΄νΉκ³Ό μμ μ±μ μν΄μλ, νμ μ μ§ν μν€λ κ²λ³΄λ€ λͺ μμ μΈ νμ ꡬ문μ μ¬μ©νλ κ²μ΄ λ«λ€.