π
26μΌμ°¨
Part 4. TypeScript Essentials
Ch 5. Interfaces
Ch 5. Interfaces
μΈλΆμ μΌλ‘ λλ¬λλ κ°μ²΄μ μ¬μ© λ°©μμ΄ μ νμλ νμ
interface Person1 {
name: string;
age: number;
}
function hello1(person: Person1): void {
console.log(`μλ
νμΈμ! ${person.name} μ
λλ€.`);
}
const p1: Person1 = {
name: "Mark",
age: 39,
};
hello1(p1);
π optional property
interface Person3 {
name: string;
age?: number; // optional property
[index: string]: any; // optional property
}
function hello3(person: Person3): void {
console.log(`μλ
νμΈμ! ${person.name} μ
λλ€.`);
}
const p31: Person3 = {
name: "Mark",
age: 39,
};
const p32: Person3 = {
name: "Anna",
systers: ["Sung", "Chan"],
};
const p33: Person3 = {
name: "Bokdaengi",
father: p31,
mother: p32,
};
hello3(p33);
π Function In Interface
interface Person4 {
name: string;
age: number;
hello(): void;
}
const p41: Person4 = {
name: "Mark",
age: 39,
hello: function (): void {
console.log(`μλ
νμΈμ! ${this.name} μ
λλ€.`);
},
};
const p42: Person4 = {
name: "Mark",
age: 39,
hello(): void {
console.log(`μλ
νμΈμ! ${this.name} μ
λλ€.`);
},
};
// thisλ₯Ό μ¬μ©νκΈ° λλ¬Έμ μ΄ μ½λμμ μ μ© λΆκ°
// const p43: Person4 = {
// name: "Mark",
// age: 39,
// hello: (): void => {
// console.log(`μλ
νμΈμ! ${this.name} μ
λλ€.`);
// },
// };
p41.hello();
p42.hello();
π Class Implements Interface
interface Iperson1 {
name: string;
age?: number;
hello(): void;
}
class Person implements Iperson1 {
name: string;
age?: number | undefined;
constructor(name: string) {
this.name = name;
}
hello(): void {
console.log(`μλ
νμΈμ! ${this.name} μ
λλ€.`);
}
}
const person: Iperson1 = new Person("Mark");
person.hello();
π Interface Extends Interface
interface Iperson2 {
name: string;
age?: number;
}
interface IKorean extends Iperson2 {
city: string;
}
const kL: IKorean = {
name: "μ΄μ
μ¬",
city: "μμΈ",
};
π Function Interface
interface HelloPerson {
(name: string, age?: number): void;
}
const helloPerson: HelloPerson = function (name: string) {
console.log(`μλ
νμΈμ! ${name} μ
λλ€.`);
};
helloPerson("Mark", 39);
π Readonly Interface Properties
interface Person8 {
name: string;
age: number;
readonly gender: string;
}
const p81: Person8 = {
name: "Mark",
gender: "male",
};
p81.gender = "female"; // Error λ³κ²½ λΆκ° (read only)
π Type Alias vs Interface
// Type Alias
type EatType = (food: string) => void;
// Interface
interface IEat {
(food: string): void;
}
π Declaration Merging - Interface
interface MergingInterface {
a: string;
}
interface MergingInterface {
b: string;
}
let mi: MergingInterface;
mi.a; // a b λ λ€ κ°λ₯ (Declaration Merging)
mi.b;