typescript interface 2

interface 정리 2

생각보다 interface의 기능이 조금 길어 두개로 나누어보았다. 그 전 내용은 링크 참조
interface1

1. function interface

함수에서 매개변수나 함수형 interface를 사용시 여러 문제 사항이 있는데 그 것을 정리해보려고 한다.
간략하게 코드를 만들어보자

1
2
3
4
5
6
7
8
9
10
interface Person{
(name:string,age?:number):void;
}
//함수형 interface

const localData:Person=function(name:string,age:number){
console.log(`hello my name is ${name}`);
}


위에서의 코드에서 문제는 무엇일까? name:string,age:number라는 곳에서 문제를 찾아볼 수 있다. localData는 결국 Person이라는 interface를 참조하였고 그 방식으로 실행하는 것인데 interface에서 age:number의 방식은 옵셔널 프로퍼티 방식이다. 값이 다르니 결국 실행되지 않으며 위와 같은 방식으로 문제를 접근한다면 좀 더 구조가 잘짜여진 코드를 만들 수 있을까 하는 생각이 든다.

2. Readonly Interface

Readonly라는 특성은 간단하다. 값은 지정가능하지만 그 값을 변경하지 못하도록 설정하는 것이다.

1
2
3
4
5
6
7
interface Person{
name:string;
age?:number;
Readonly id:number
}
//id 값은 변경불가능

3. intersection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface ErrorHandling{
isSuccess:boolean;
isError?:{msg:string}

}

interface UserData{
name:string;
age?:number;
}

type UserDataCheckResponseType=UserData&ErrorHandling
// type alias

interface IsUserDataCheckResponse extends UserData,ErrorHandling{}
// 다중 상속

intersection 방식은 공부 할 부분이 제법 되는 부분 같다. 다중 상속과 interface의 연계등 좀 더 많은 예시를 보면서 손과 눈에 익혀보도록 해보려고 계획을 해봐야겠다.

3. Merging interface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface UserData{
name:string;
age?:number;

}

interface UserData{
id:number;
}

let data:UserData;
// id,name,age 의 사용이 다되도록 Merging이 자동으로 된다
// type alias 는 Merging 사용이 불가능하다.