TypeScript - Interfaces
2022. 2. 27. 21:22ㆍ공부/TypeScript
What are Interfaces??
: 타입을 만들어내는 방식.
javascript에는 존재하지 않으므로 실제 컴파일 될 경우 사라지게 된다.
컴파일 타입에만 사용하며 각 구조 간 관계를 규명하여 체크하는 용도로 사용한다.
예시
Interface 없는 버전
function hello1(person: {name: string, age: number}): void{
console.log(`안녕하세요! ${person.name}입니다.`);
}
const p1 : {name: string, age: number} ={
name: "mark",
age: 39
};
hello1(p1);
Interface 있는 버전
interface Person1 {
name: string;
age: number;
}
function hello1(person: Person1): void{
console.log(`안녕하세요! ${person.name}입니다.`);
}
const p1 : Person1 ={
name: "mark",
age: 39
};
hello1(p1);
컴파일 후 JavaScript 파일
"use strict";
function hello1(person) {
console.log(`안녕하세요! ${person.name}입니다.`);
}
const p1 = {
name: "mark",
age: 39
};
hello1(p1);
optional property (1)
있어도 되고 없어도 되는 속성은 속성명 뒤에 ?를 넣는다.
예시
interface Person2 {
name: string;
age?: number; // age가 있어도 되고 없어도 되는 속성이면 뒤에 ?를 붙인다.
}
function hello2(person: Person2): void {
console.log(`안녕하세요! ${person.name} 입니다.`);
}
hello2({name: 'Mark', age: 39});
hello2({name: "Anna"});
optional property (2)
객체의 인덱스를 임의의 프로퍼티로 받겠다는 의미
어떤 이름, 어떤 형식의 프로퍼티를 추가로 넣어도 괜찮을 때 사용한다.
예시
interface Person3 {
name: string;
age?: number;
[index: string]: any; //인덱스를 스트링으로 넣겠다는 의미. 어떤 프로퍼티가 와도 된다.
}
function hello3(person: Person3): void {
console.log(`안녕하세요! ${person.name} 입니다.`);
}
const p31: Person3 = {
name: 'Mark',
age: 39,
};
const p32: Person3 = {
name: 'Anna',
sisters: ['Sung', 'Chan'],
};
const p33: Person3 = {
name: 'BokdaenI',
father: p31,
mother: p32, // 여러개 넣어도 됨.
};
hello3(p31); // 안녕하세요! Mark 입니다.
hello3(p32); // 안녕하세요! Anna 입니다.
hello3(p33); // 안녕하세요! BokdaenI입니다.
console.log(p33[`father`]); // { name: 'Mark', age: 39 }
function in interface
인터페이스 안에 함수를 넣을 수 있다.
함수를 넣는 방법은 총 세가지가 있는데 다음과 같다.
- function 키워드 사용
- function 키워드 생략
- Arrow function 사용 : this는 사용할 수 없다.
예시
interface Person4 {
name: string;
age: number;
hello(): void;
}
const p41: Person4 = {
name: 'Mark1',
age: 39,
hello: function(): void {
console.log(`안녕하세요! ${this.name}입니다.`);
},
};
const p42: Person4 = {
name: 'Mark2',
age: 39,
hello(): void {
console.log(`안녕하세요! ${this.name}입니다.`);
},
};
const p43: Person4 = {
name: 'Mark3',
age: 39,
hello: (): void => {
console.log(`안녕하세요! ${p43.name}입니다.`);
},
};
p41.hello(); // Mark1
p42.hello(); // Mark2
p43.hello(); // Mark3
class implements interface
클래스의 인터페이스를 정의하는 것.
외부와 상호작용하는 인터페이스를 만들어서 클래스의 내부 정보를 보호한다.
예시
interface IPerson1 {
name: string;
age?: number;
hello(): void;
}
class Person implements IPerson1 {
name: string;
age?: number | undefined;
constructor(name: string) { // age는 undefined가 가능하니 굳이 안넣어줘도 된다.
this.name = name;
}
hello(): void{
console.log(`안녕하세요! ${this.name}입니다.`)
}
}
const person: IPerson1 = new Person("Mark");
// 클래스 이름 또는 인터페이스 이름으로 속성을 정의할 수 있다.
// 외부로는 인터페이스만 드러내고 내부로는 클래스로 정의하는 것.
person.hello();
interface extends interface
인터페이스는 인터페이스를 상속할 수 있다.
예시
interface IPerson2 {
name: string;
age?: number;
}
interface IKorean extends IPerson2 {
city: string;
}
const k: IKorean = {
name: 'Mark',
city: 'seoul',
age: 39
};
function interface
함수의 인터페이스. 함수의 매개변수보다 인터페이스를 먼저 따른다.
예시
interface HelloPerson {
(name: string, age?: number): void;
}
const helloPerson: HelloPerson = function (name: string) {
console.log(`안녕하세요! ${name}입니다.`)
}
helloPerson("Mark", 39) // 이렇게 해도 문제가 발생하지 않는다.
// 함수의 매개변수보다 HelloPerson이라는 인터페이스가 더 중요시됨.
const helloPerson2: HelloPerson = function (name: string, age: number|undefined) { // 여기서 age: number로만 정의하면 에러가 발생한다.
console.log(`안녕하세요! ${name}입니다.`)
}
helloPerson("Jane", 28)
const helloPerson3: HelloPerson = function (name: string, age?: number) {
console.log(`안녕하세요! ${name}입니다.`)
}
helloPerson3("Doriam", 29)
Readonly Interface Properties
인터페이스 속성에 읽기전용 속성을 추가하는 것.
한 번 만들어지고 바뀌지 않는 속성
예시
interface Person8 {
name: string;
age?: number;
readonly gender: string;
}
const p81: Person8 = {
name: "Mark",
gender: "male",
};
p81.gender = "female"; // 읽기전용이라 에러가 발생한다.
'공부 > TypeScript' 카테고리의 다른 글
TypeScript - Generic, keyof (0) | 2022.02.28 |
---|---|
TypeScript - Class (0) | 2022.02.27 |
TypeScript - TSconfig.json 설정들 (0) | 2022.02.27 |
Type Script - Type Alias, Interface (0) | 2022.02.27 |
TypeScript - 타입 호환성 (0) | 2022.02.27 |