μΌ | μ | ν | μ | λͺ© | κΈ | ν |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- λ΄μΌλ°°μμΊ ν
- 리μ‘νΈ
- Redux
- JavaScript
- rn
- K-Digital
- type
- νμ
- μλ¬
- μκ³ λ¦¬μ¦
- JS
- react
- μ¨λΌμΈ
- νλ‘ νΈμλ
- trainning
- PROJECT
- μλ°μ€ν¬λ¦½νΈ
- Firebase
- νλ‘μ νΈ
- API
- ν¨μ
- λΆνΈμΊ ν
- μ½λ©
- λ΄μΌλ°°μ
- νμ€
- NEXT
- κ°λ°μ
- wil
- λ³μ
- native
Archives
- Today
- Total
Frontend κ°λ°μ - hyo.loui
νμ μ€ν¬λ¦½νΈ - Union (μ λμ¨) νμ λ³Έλ¬Έ
π―λͺ©μ :
Type Script Union μ λμ¨|μ λμΈ νμ , μ 리 λ° λ³΅μ΅
1. μ λμ¨ νμ μ΄λ?
νμ μ "or μ°μ°μ"λ‘ 2κ° μ΄μ λ£μ μ μκ² ν΄μ€λ€
// Union (A || B)
const printOut = (input: string | number) => {
console.log(input);
};
printOut("hi"); // hi
printOut(22); // 22
π§ͺλμ μ€νμ€
// Union (A || B)
const printOut = (input: string | number) => {
return input;
};
const test_ = typeof printOut("hi"); // hi
console.log("ππ test_", test_); //ππ test_ string
const test__ = typeof printOut(22); // 22
console.log("ππ test__", test__); // ππ test__ number
typeof λ‘ μ€μ νμ μ΄ λ§λμ§ μ½μμ μΆλ ₯ ν΄ λ³΄μλ€ ( μ μ )
2. μ λμ¨ νμ μ μ₯μ
νλμ νλΌλ―Έν°κ°
2κ°μ§ νμ μ λμμ μνν μ μκ³ , λ€λ₯Έ νμ μ μλ¬λ‘ κ±°λ₯Ό μ μλ€.
const getAge = (age: number | string) => {
if (typeof age === "number") {
age.toFixed();
return age;
}
if (typeof age === "string") {
return age;
}
};
console.log(getAge(12), typeof getAge(12)); // 12 number
console.log(getAge("12"), typeof getAge("12")); // 12 string
3. νμ λ³λ‘ λ€λ₯Έ λμ ꡬν
νλΌλ―Έν°μ λ€μ΄μ€λ νμ μ ifλ¬ΈμΌλ‘ μ λ³νμ¬,
κ° λ€λ₯Έ λμμ μ·¨ν μ μλ€.
λ§μ½ numberκ° λ€μ΄μ¨λ€λ©΄ paddind (space) κ° λμ΄λλλ‘ νκ³ ,
stringμ΄ λ€μ΄μ¨λ€λ©΄ value μμΌλ‘ string(λ¬Έμμ΄)μ΄ λ€μ΄μ€κ² νμλ€.
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
if (typeof padding === "string") {
return padding + value;
}
throw new Error(`Expected string or number, get ${padding}.`);
}
console.log(padLeft("Hello world", 4)); // Hello world
console.log(padLeft("Hello world", "!!!")); // !!!Hello world
// console.log(padLeft("Hello world", true));// Error
μ΅μ’ μ 리
- μ λμ¨μ νμ μ 2κ°μ§ μ΄μ μ¬μ©ν μ μκ² λ§λ€μ΄ μ€λ€
- νμ κ³Ό νμ μ¬μ΄μ, or μ°μ°μ "|" λ₯Ό μ¬μ©νλ©΄ λλ€.
- νμ μ μ λ³νμ¬ κ°κΈ° λ€λ₯Έ λμμ νλλ‘ λ§λ€μ΄ μ€ μ μλ€.
'Typescript' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
νμ μ€ν¬λ¦½νΈ - interface (μΈν°νμ΄μ€) (0) | 2023.01.18 |
---|---|
νμ μ€ν¬λ¦½νΈ - Type Alias (νμ λ³μΉ) (0) | 2023.01.18 |
νμ μ€ν¬λ¦½νΈ - Enum (μ΄λ) (0) | 2023.01.17 |
νμ μ€ν¬λ¦½νΈ - Function (ν¨μ) νμ (0) | 2023.01.17 |
νμ μ€ν¬λ¦½νΈ - κΈ°λ³Έ νμ (0) | 2023.01.17 |