Java 프로그래밍 언어에서 interface는 Class의 규격을 지정하는 데 사용되는 추상 자료형입니다. 상속받은 interface의 구현을 강제하여 코드의 일관성을 유지시키는 데 도움이 됩니다.
TypeScript에선, interface를 타입 체크를 위해 클래스 뿐만 아니라 변수, 함수에도 사용할 수 있습니다. interface를 타입으로 선언하거나 상속받은 개체는 interface를 준수해 구현해야 합니다.
1. 변수에 인터페이스 적용
- 변수의 규격을 지정할 수 있습니다.
// 사람이라면, 이름과 나이가 있어야 한다
interface Person {
name: string;
age: number;
};
// 변수에 인터페이스를 적용
const p1: Person = {
name: 'mark',
age: 39,
father: "Steve" // 오류: interface에 지정된 property가 아님
};
// 함수 인자에 인터페이스를 적용
function hello1(person: Person): void {
console.log(`${person.name}(${person.age})`);
}
2. 함수에 인터페이스 적용
- 함수의 규격을 지정할 수 있습니다.
// 제곱하는 함수는 number 타입의 인자를 받고, number 타입의 반환 결과를 가져야 한다
interface SquareFunc {
(num: number): number;
}
// 함수에 인터페이스를 적용
const squareFunc: SquareFunc = function(x: number): number {
return x * x;
}
3. 클래스에 인터페이스 적용
- 클래스의 규격을 지정할 수 있습니다.
interface Person {
name: string,
age: number
}
class Hyeonjun implements Person {
// Person interface의 name과 age 멤버 변수를 선언해야 한다.
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
4. 인터페이스 상속
- interface는 선언 병합을 통해 확장시킬 수 있습니다.
- interface는 extends 키워드를 통해, 다른 interface를 상속받을 수 있습니다.
interface Person {
name: string;
age: number;
}
// override
interface Person {
height: number;
}
// inherit
interface Developer extends Person {
skills: Array<string>
}
5. optional property
- interface의 값이 있을 수도 있고, 없을 수도 있는 값을 지정할 수 있습니다.
// 사람은 이름이 있어야 하며, 취미는 있을 수도 있고 없을 수도 있다.
interface Person {
name: string;
hobby?: string; // optional property
}
const person: Person = { name:'Mark' };
6. indexable property
- 특정한 타입을 가지는 index와 리턴 타입을 가지는 property들을 만들 수 있게 해줍니다.
interface Person {
name: string;
[index: string]: any; // string 타입의 인덱스로 잡근하면, any 타입의 결과물을 줄것이라다고 명시
electronics: object;
}
const person: Person = {
name: 'Lucas',
/* indexable property 적용 */
family: { // object에 string index로 접근하면 any(string)을 리턴을 정의
father: 'Oliver',
mother: 'Lily'
},
books: [ "Refactoring", "Nodejs" ], // array에 string index로 접근하면 any(string)을 리턴을 정의
/* end */
electronics: {
phone: 'iphone',
pad: 'ipad'
}
}
console.log( person.family['mother'] );
console.log( person.books['0'] );
console.log( person.electronics['phone'] ); // 오류
/*
오류: indexable property를 지정하지 않으면,
리턴값이 암묵적인 any 타입이기 때문에, noImplicitAny 옵션의 영향으로 오류가 발생한다.
*/
7. readonly property
- 읽기 전용 property를 만들 수 있습니다.
interface Person {
name: string;
age: number;
readonly gender: string
}
'JavaScript > Typescript' 카테고리의 다른 글
TypeScript - class (0) | 2022.01.13 |
---|---|
TypeScript - 타입 호환성 (0) | 2022.01.10 |
TypeScript - Type System (0) | 2022.01.10 |
TypeScript - Type의 종류 (1) | 2022.01.10 |
TypeScript - 기본 개념과 설치해보기 (0) | 2022.01.06 |