TIL

[TIL] 2021년 12월 28일

건브로 2021. 12. 28. 21:48

1. 오늘 한 것

 

interface에 대한 공부

정보처리기사 공부

 

2. interface에 대한 공부

 

interface는 객체지향 프로그래밍 언어에서 보이는 키워드다.

 

근데, 자바스크립트에서는 interface를 사용할 수 없다.

 

자바스크립트는 느슨하고, 브라우저에서 사용하는 언어이기 때문인 것 같다.

 

최근에 자바스크립트를 봤을 때는 private, public에 대한 접근자가 나와 있었다.

 

나중엔 interface도 구현되어 있지 않을까 싶다.

 

//TypeScript
//객체에 사용하는 인터페이스
interface FoodShape {
    name: string;
    taste: string;
    eatFood(): void;
}
let food1: FoodShape;
food1 = {
    name: 'seasoned chicken',
    taste: 'spicy',
    eatFood(){
    	console.log(`${this.name}을(를) 먹는다.`);
    }
}
food1.eatFood();

 

//TypeScript
//클래스에 사용하는 인터페이스
interface Shape {
	name: string;
}
//?키워드를 써서 소개 속성이 필수가 아님을 알려준다.
//readonly 키워드는 한 번 생성하면 바꿀 수 없고, 읽기만 가능하다.
interface FoodShape extends Shape {
    readonly taste: string;
    introduction?: string;
    eatFood(): void;
}

interface Origin {
	nation?: string
}
//class 상송과는 다르게 여러 개의 인터페이스를 명세서로써 사용해도된다.
class Food implements FoodShape, Origin{
    //1. 이렇게 간략하게 써도 된다.
    //constructor(public name: string, public taste: string){}
    //2. 평범한 방법
    name: string;
    taste: string;
    constructor(n: string, t: string){
    	this.name = n;
        this.taste = t;
    }
    eatFood(){
    	console.log(`${this.name}을(를) 먹는다.`);
    }
    tasteFood(){
    	console.log(`이 ${this.name}의 맛은 ${this.taste}이다.`);
    }
}

const food2 = new Food('chicken', 'spicy');
food2.eatFood();
//chicken을(를) 먹는다.
food2.tasteFood();
//이 chicken의 맛은 spicy이다.

 

//TypeScript
//함수에서 사용하는 interface
interface CreateFunc {
  (elName: string, content: string): void;
}

const createElAtBody: CreateFunc = (elName: string, content: string) => {
  const el = document.createElement(elName);
  el.textContent = content;
  const body = document.querySelector("body");
  if (body) {
    body.appendChild(el);
  }
};
createElAtBody("button", "확인");

 

 

3. 느낀 점

 

옛날에 interface와 class의 진짜 기능을 잘 몰랐는데, 지금은 감이 잡힌다.

 

그리고 이러한 부분을 왜 두려워했는지 알 것 같다.

 

외울게 많아서 내가 두려워했던 것 같다.

 

이해도 안 됐기도 했고...

 

그래도 이번엔 이해가 되었으니 자주 사용하자!

 

'TIL' 카테고리의 다른 글

[TIL] 2022년 01월 07일  (0) 2022.01.07
[TIL] 2022년 01월 6일  (0) 2022.01.06
[TIL] 2021년 12월 27일  (0) 2021.12.27
[TIL] 2021년 12월 23일  (0) 2021.12.23
[TIL] 2021년 12월 21일  (0) 2021.12.21