(μλ¬ ν΄κ²°) Union typeκ³Ό νμ κ°λ ν¨κ» μ¬μ©νκΈ°
Union type
|
μ°μ°μλ‘ μ¬λ¬ κ°μ νμ
μ΄ μ°κ²°λ νμ
μ μλ―Ένλ€. μ΄λ |
μ°μ°μλ orμ μλ―Έλ₯Ό κ°μ§κ³ μλ€. μ΄λ¬ν Union typeμ νμ©ν΄ μΈν°νμ΄μ€λ₯Ό μ μνκ³ μ νλ€.
λ¬Έμ μ μ
interface Props {
data: LectureRoomsPerBuilding | LectureRoomInfo;
children?: LectureRoomInfo[];
}
λ€μκ³Ό κ°μ΄ μΈν°νμ΄μ€λ₯Ό μμ±νλλ°, νμ μΆλ‘ μμ λ¬Έμ κ° λ°μνλ€.
export interface LectureRoomInfo {
room_name: string;
room_uid: RoomUID;
}
export interface LectureRoomsPerBuilding {
building_name: string;
building_uid: number;
rooms: LectureRoomInfo[];
}
μλ¬κ° λ°μν μ½λλ data.room_name
data.building_name
μ΄μλ€. "LectureRoomsPerBuildingμ room_name νλ‘νΌν°λ₯Ό ν¬ν¨νμ§ μλλ€." "LectureRoomInfoλ building_name νλ‘νΌν°λ₯Ό ν¬ν¨νμ§ μλλ€." λΌλ μλ¬ λ©μμ§λ₯Ό νμΈν μ μμλ€. orμ μλ―Ένλ | μ°μ°μλ‘ λ νμ
μ μ°κ²° νμΌλ λ μΈν°νμ΄μ€μ νλ‘νΌν°λ€μ λͺ¨λ μ¬μ©ν μ μμκ±°λΌ μκ°νλλ° λ΄ μμμ΄ νλ Έμλ€.
Union Typeμ λν΄ κ΅¬κΈλ§ν κ²°κ³Ό μ΄μ κ΄λ ¨λ μλ£λ₯Ό μ°Ύμ μ μμλ€.
Union Type μ¬μ© μ μ£Όμμ
https://joshua1988.github.io/ts/guide/operator.html#intersection-type
interface Person {
name: string;
age: number;
}
interface Developer {
name: string;
skill: string;
}
function introduce(someone: Person | Developer) {
someone.name; // O μ μ λμ
someone.age; // X νμ
μ€λ₯
someone.skill; // X νμ
μ€λ₯
}
νμ μ€ν¬λ¦½νΈ μ μ₯μμλ introduce ν¨μ μ€ν μ μΈμλ‘ Personμ΄ μ¬ μ§, Developerκ° μ¬ μ§ μ μ μλ€. λ°λΌμ λ μ€ μ΄λ νμ μ΄ μλ μ€λ₯κ° λμ§ μλ λ°©ν₯μΌλ‘ νμ μ μΆλ‘ νλ€. κ°λ Ή μΈμλ‘ Developer νμ μ΄ μ¨λ€λ©΄ someone.age λΌλ μ½λλ μλ¬λ₯Ό λ°μμν€κΈ° λλ¬Έμ νμ μ€ν¬λ¦½νΈκ° 미리 μλ¬λ₯Ό λμ°λ κ²μ΄λ€.
νμ κ°λ
μ΄λ₯Ό ν΄κ²°νκΈ° μν΄μ νμ κ°λλ₯Ό μ΄μ©ν΄μΌ νλ€.
νμ κ°λλ? ν¨μ λ΄μμ 쑰건문μ μ¬μ©ν΄ νμ μ μ’νλ κ²
function Hello(user: string|number){
if (typeof user === 'string'){
// νμ
μ stringμΌλ‘ μ’νλ€
console.log(`Hello ${user}`);
}
console.log(`Hello ${users[user]}`);
}
ν¬κ² λ κ°μ§ λ°©λ²μ΄ μλ€.
- typeof: μμ μλ£νλ§ κ΅¬λΆν μ μλ€.
- in: κ°μ²΄μ νΉμ νλ‘νΌν°κ° μ‘΄μ¬νλμ§λ₯Ό νμΈν¨μΌλ‘μ¨ νμ μ μ’νλ€.
λλ LectureRoomInfo
μ LectureRoomsPerBuilding
μ ꡬλΆν΄μΌ νκΈ° λλ¬Έμ, λλ²μ§Έ λ°©λ²μ μ¬μ©νλ€.
νμ κ°λλ₯Ό μ μ©ν ν¨μ
const updateLectureRoomChoice = () => {
if ('room_name' in data) {
setLectureRoomChoice({
building_uid: data.building_uid,
room_uid: data.room_uid,
});
}
};
props data
μ room_name
νλ‘νΌν°κ° μ‘΄μ¬νλ€ == data
κ° LectureRoomInfo
νμ
μ΄λ€. == μλΈλ©λ΄μ ν΄λΉνλ€.
μ λ² κΈμμλ λ©μΈλ©λ΄μ μλΈλ©λ΄λ₯Ό children propsμ μ¬λΆλ‘ ꡬλΆνμλλ°, μ΄λ κ² νμ κ°λλ₯Ό νμ©ν΄ ꡬλΆν μλ μμλ€. λ€λ§ νμ κ°λμ κ²½μ° jsxμμ 곧λ°λ‘ μ¬μ©ν μ μμΌλ―λ‘ UIμμλ children propsμ, ν¨μ λ΄μμλ νμ κ°λλ₯Ό μ¬μ©νλ λ°©μμ νν΄μΌκ² λ€.
μ μμμ²λΌ dataμ νλ‘νΌν°μ μ κ·Όνλ ν¨μλ€μ λͺ¨λ νμ κ°λλ₯Ό μ μ©ν΄ 쀬λλ μλ¬κ° ν΄κ²°λμλ€!