외부적으로 드러나는 어떤 개체의 사용 방식이 적혀있는 타입.
inerface Person1 {
name: string;
age: number;
}
function hello(person: Person1): void {
console.log(`${person.name} 안녕`);
}
const p1: Person1 = {
name: "mark",
age: 14
};
hello(p1);
인터페이스는 JS에는 없다.
컴파일 타임에서만 이용하기 위해서 사용하는 것.
inerface Person2 {
name: string;
age?: number; //? 는 있을 수도 있고 없을 수도 있다는 의미
}
function hello2(person: Person2): void {
console.log(`${person.name} 안녕`);
}
hello2({name: "dd", age: 33});
hello2({name: "ddd"});
inerface Person3 {
name: string;
age?: number; //? 는 있을 수도 있고 없을 수도 있다는 의미
[index: string]: any;//어떤 것이든 들어올 수 있다는 의미
}
function hello3(person: Person3): void {
console.log(`${person.name} 안녕`);
}
const p31: Person3 = {
name: 'mark'
};
const p32: Person3 = {
name: 'any',
age: 33,
systers: ['amy', 'ee']
};
const p33: Person3 = {
name: 'kk',
father: p31,
mother: p32
};
hello2({name: "dd", age: 33});
hello2({name: "ddd"});
inerface Person4 {
name: string;
age: number;
hello(): void; //함수!
};
const p41: Person4 = {
name: 'mark',
age: 33,
hello: funtion(): void {
console.log(`안녕 ${this.name}`);
}
};
const p42: Person4 = {
name: 'mark',
age: 33,
hello(): void {
console.log(`안녕 ${this.name}`);
}
};
p41.hello();
p42.hello();
//컴파일 하고 node로 js 파일 실행하기
inerface 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 = new Person("mark");
const person1: IPerson1 = new Person("dd");
인터페이스에서 클래스를 implements 하는 방법이다.
inerface IPerson2 {
name: string;
age?: number;
};
interface IKorean extends IPerson2 { //IPerson2 상속
city: string;
}
const k: IKorean = {
name: 'lala',
city: "서울"
};
인터페이스끼리 상속하는 방법이다.
interface HelloPerson {
(name: string, age?: number): void;
}
const helloPerson: HelloPerson = function(name: string) {
console.log(`안녕 ${this.name}`);
};
const helloPerson: HelloPerson = function(name: string, age: number) {
console.log(`안녕 ${this.name}`);
};
//이렇게 하면 에러가 난다.
//age? 와 age 의 차이 때문이다.
helloPerson("mark", 33); //얘는 위의 helloPerson 보다는 HelloPerson와의 관계만 본다.
inerface Person8 {
name: string;
age?: number;
readonly gender: string;
};
const p81: Person8 = {
name: 'mark',
gender: 'male'
}
p81.gender = 'female'; //이것은 에러 발생한다.
//readonly기 때문에 수정은 불가능하다.
//사용자에게 작성자의 의도 알려주는 의미.
function, array, intersection, union types 등 type alias와 interfac의 작성법의 차이 ...
interface에서만 가능하다!
interface Merging {
a: string;
}
interface Merging {
b: string'
}
let mi: Merging; //위의 두개가 병합된다.