typescript interface 1

interface 정리

한번 더 정리한다는 생각으로 다시 typescript를 정리해보려고 한다. 먼저 interface 사용방식만 간략하게 정리해보려고 한다.

1. Optional property

1
2
3
4
5
6
7
8
9
interface User{
id:number;
name:string;
age:number;
gender?:"male"|"female";
// 1번 Optional property
[index:string]:any;
// 2번 Optional property
}

1번 Optional property는 간략하게 값이 있을수도 있고 없을 수도 있다는 뜻이다. 그 값이 필수가 아니라는 것이기에 옵션이라는 의미에 매우 적합하다. 사용예시는 간단하다

1
2
3
4
5
6
7
8
9
10
const kim:User={
id:1, name:"kim gi tae",age:33
}
// Optional property noting

const kim2:User={
id:1, name:"kim gi tae",age:33,skills:["game","painting"]
}


한사람의 데이터를 정의할때 위와 같은 User interface를 지정하고 그 데이터에서 반드시 필요한 id,name,age는 정의하지만 다른 데이터는 정의할 필요가 없다. 그것이 Optional property 이다.

2번 Optional property는 필요한 값을 자신이 편하게 만들수 있다는 의미의 Optional property라고 할 수 있다.
사용예시 같은 경우는 위의 예시와 같이 그 데이터에서 필요한 skills과 같은 값을 지정하고 내부 값은 string으로 지정하겠다라는 옵션적인 선언 방식이다.

2. fuction in interface

interface에서는 간단히 함수도 지정할수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface User{
id:number;
name:string;
age:number;
gender?:"male"|"female";
[index:string]:any;
getData():void;
}

const kim:User={
id:1,
name:"kim gi tae",
age:33,
getData():void{
console.log(`안녕하세요!${this.name}입니다`)
}
}

void라는 방식으로 지정한다면 값을 return 하지 않고 실행만하는 방식으로 지정한다는 뜻이다. 위의 예시의 kim 변수와 같이 말이다.
재미있는 건 getData()의 내부 값에서 this의 값도 interface로 지정이 가능하다는 것이다.
getData(this:User)라고 지정하는 것으로 this는 User의 규칙을 맞춰서 쓰는 것이 가능해진다라는 것이다.

3. class implements interface

아까전 만들어둔 interface를 통해서 class를 만들수도 있다.
implements라는 방식을 통해서 만드는 것인데 매우 간단하게 class 생성이 가능해진다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
interface User{
id:number;
name:string;
age:number;
gender?:"male"|"female";
[index:string]:any;
getData():void;
}

class UserData implements User{
id:number;
name:string;
age:number;
gender?:"male"|"female";
constructor(name:string){
this.name=name
}
getData():void{
console.log(`안녕하세요${this.name} `)
}

}

interface에 담겨진 데이터를 매우 쉽게 재규정할 수 있으며 좀 더 확실한 규칙으로 객체를 만들기 쉽다고 느껴졌다.

4. interface extends interface

interface의 상속도 매우 간단하다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface User{
id:number;
name:string;
age:number;
gender?:"male"|"female";
[index:string]:any;
getData():void;
}

interface gameUser extends User{
char:string;

}

전체적인 상속을 통해서 필요한 데이터를 추가하고 개별적으로 사용가능하니 재사용성도 무척 좋다고 생각된다.