๋ ์ปค์คํ ํ์ ์ด Dog์ Fish๋ฅผ ์์ฑํด๋ณด์.
ํด๋์ค๋ก ์ ์ธํ๊ณ name ํ๋กํผํฐ๋ฅผ ์ถ๊ฐ.
Dogํด๋์ค๋ sayHello(): string ๋ฉ์๋๋ฅผ ๊ฐ์ง
Fishํด๋์ค๋ dive(howDeep: number): string๋ฉ์๋๋ฅผ ๊ฐ์ง
ํ์ Pet์ ์ด์ฉํด Dog์ Fish์ ์ ๋์จ ํ์ ์ผ๋ก ์ ์ธ.
talkToPet(pet: Pet):stringํจ์๋ ํ์ ๊ฐ๋๋ฅผ ์ฌ์ฉํด Dogํด๋์ค๋ฉด sayHello, Fish๋ฉด 'Fish cannot talk, sry'๋ฅผ ์ถ๋ ฅ
talkToPet()์ ํ๋ผ๋ฏธํฐ๋ฅผ Dog, Fish, ๊ทธ์ธ ๊ฐ์ฒด๋ก ์ด 3๋ฒ ํธ์ถํจ.
// 2_30.ts
class Dog{
constructor(readonly name: string){};
sayHello(): string{
return 'Dog Say Hello!'
}
}
class Fish{
constructor(readonly name: string){};
div(howDeep: number): string{
return `Diving ${howDeep} feat`;
}
}
type Pet = Dog | Fish; // ์ ๋์จ ํ์
function talkToPet(pet: Pet): string{
if(pet instanceof Dog){ // ํ์
๊ฐ๋
return pet.sayHello();
}else if(pet instanceof Fish{
return 'Fish cannot talk, sry';
}
}
const myDog = new Dog("Sammy");
const myFish = new Fish("Nimo");
console.log(talkToPet(myDog));
console.log(talkToPet(myFish));