타입을 만들어내는 방식..?
차근 차근 알아보자
function helloInter(person: { name: string; age: number }): void {
console.log(`안녕하세요! ${person.name}입니다. `);
}
const p1: { name: string; age: number } = {
name: "mark",
age: 39,
};
helloInter(p1);
interface person1 {
name: string;
age: number;
}
function helloInter(person: person1): void {
console.log(`안녕하세요! ${person.name}입니다. `);
}
const p1: person1 = {
name: "mark",
age: 39,
};
helloInter(p1);
처음으로 interface를 만든것이다.!!
자바스크립트에 없는 인터페이스 문법이 컴파일했을때 자바스크립트에서는 어떻게 나올까?
"use strict";
function helloInter(person) {
console.log(`안녕하세요! ${person.name}입니다. `);
}
const p1 = {
name: "mark",
age: 39,
};
helloInter(p1);
엥? 없다. 아무리봐도 interface는 안보인다.
컴파일 타임에만 interface를 이용해서 에러를 체크한다.
interface Person2 {
name: string;
age?: number;
}
물음표를 붙여주면 된다.
이렇게 있을수도 있고 없을 수도 있고!!
interface Person3 {
name: string;
age?: number;
[index: string]: any;
}
// a['index'] -> ["whatever"] -> ["ㅇㅁㄴㅇㅁㄴㅇㅁㄴㅇㄴㅁ"]
function hello4(person: Person3): void {
console.log(`안녕하세요 ${person.name} 입니다.`);
}
const p31: Person3 = {
name: "mark",
age: 29,
};
const p32: Person3 = {
name: "anna",
systers: ["sung", "chan"],
};
const p33: Person3 = {
name: "Bokda",
father: p31,
mother: p32,
};
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}`);
},
};
const p43: Person4 = {
name: "mark",
age: 39,
hello: (): void => {},
// 화살표함수는 this 못쓴다.
};
실행결과!
personIC.hello();
이렇게 할 수 있다.
interface 상속은 이런식으로도 쓰인다.
interface 상속은 나중에 대규모 프로젝트를 진행할 때 유용하게 쓰일 수 있을것 같다.
함수에 대해서 인터페이스를 만들어내는 방법
이렇게 사용한다.
이렇게 사용하면 에러임!
하지만 이건 된다??
helloPerson1 은 인터페이스 helloPerson과의 관계가 중요하기 때문!
그래서 이건 당연히 안된다.
왜냐면 number는 옵셔널한 프로퍼티인데 함수에서 age를 당연히 있어야 한다고 말해버리기 때문에 에러를 발생시킨다.
//alias
type EatType = (food: string) => void;
//interface
interface IEat {
(food: string): void;
}
//alias
type personList = string[];
//interface
interface IPersonList {
[index: number]: string;
}
// intersection
interface ErrorHandling {
succes: boolean;
error: { message: string };
}
interface ArtistData {
artists: { name: string }[];
}
type ArtistResponseType = ArtistData & ErrorHandling;
interface IArtistResponse extends ArtistData, ErrorHandling {}
let art: ArtistResponseType;
let iar: IArtistResponse;
interface Bird {
fly(): void;
layEggs(): void;
}
interface Fish {
swim(): void;
layEggs(): void;
}
type PetType = Bird | Fish;
interface Ipet extends PetType {} //유니온 타입은 인터페이스한테 상속할 수 없음.
class pet implements PetType {} //클래스한테 넣어줄 수 없음.
interface merging {
a:string
}
interface merging {
b:string
}
// 이름이 같은 인터페이스를 사용하면 나중에 사용할 때 알아서 합쳐짐
// 알리아스는 이름이 겹친다고 에러가 발생함!
let mi:merging;
mi.을 하면 a와 b 를 둘 다 쓸 수 있다.