
알고있으면 좋은 Typescript Tip✨
인터페이스(interface)란?
- 상호 간의 정의한 약속 혹은 규칙을 의미하는데, 쉽게 말하면 인터페이스에 선언된 프로퍼티 또는 메서드의 구현을 강제하여 일관성을 유지할 수 있도록 하는 것이다.
(1) 인터페이스 선언
interface User {
age: number;
name: string;
}
// 변수에 활용한 인터페이스
const name: User = {
// 인터페이스 User의 구조와 같은 객체 구조를 만들지 않으면 문법 오류가 뜸
age: 33,
name: 'Kim',
}
- 인터페이스 생성 시 interface 키워드를 이용하여 생성한다.
- interface 선언시 이름은 대문자로 시작한다.
- 완성된 인터페이스는 타입처럼 사용 가능하다.
- 인터페이스를 타입으로 가지는 값은 인터페이스의 구조를 강제로 가진다.
(2) 인터페이스를 사용하지 않고 코드를 작성한다면?
function setinSideWaterLevel(before: number, today: number, month: number){
const gypgBefore: HTMLDivElement | null = document.querySelector("#gypg-before");
const gypgToday: HTMLDivElement | null = document.querySelector("#gypg-today");
const gypgMonth: HTMLDivElement | null = document.querySelector("#gypg-month");
if(gypgBefore && gypgToday && gypgMonth){
gypgBefore.innerText = rf.before.toString();
gypgToday.innerText = rf.today.toString();
gypgMonth.innerText = rf.month.toString();
}
}
// 임시 데이터
const sampleData1 = {
before: 0,
today: 10,
month: 257
};
// 함수 실행
async function init() {
setRainfallGYPG(sampleData1);
}
window.addEventListener('DOMContentLoaded', function () {
init();
});
(3) 인터페이스를 사용하여 코드를 작성한다면?
interface rainFallData {
before : number;
today : number;
month : number;
}
function setRainfall(rf: rainFallData){
const gypgBefore: HTMLDivElement | null = document.querySelector("#gypg-before");
const gypgToday: HTMLDivElement | null = document.querySelector("#gypg-today");
const gypgMonth: HTMLDivElement | null = document.querySelector("#gypg-month");
if(gypgBefore && gypgToday && gypgMonth){
gypgBefore.innerText = rf.before.toString();
gypgToday.innerText = rf.today.toString();
gypgMonth.innerText = rf.month.toString();
}
}
// 임시 데이터
const sampleData1 = {
before: 0,
today: 10,
month: 257
};
// 함수 실행
async function init() {
setRainfallGYPG(sampleData1);
}
window.addEventListener('DOMContentLoaded', function () {
init();
});'Study > TypeScript' 카테고리의 다른 글
| [TS] 함수 반환 타입 (Function Return Types) (0) | 2023.10.18 |
|---|---|
| [TS] 타입 단언 (Type Assertion) (0) | 2023.10.18 |
| [TS] basic Union Type & Intersection Type (0) | 2023.10.12 |
| [TS] 기본 자료형 타입 선언 (0) | 2023.10.11 |
| [TS] 타입스크립트 설치하기 (0) | 2023.10.11 |