[새싹x코딩온] 풀스택 개발자 부트캠프 과정 13 주차-1 TypeScript
TypeScript📌
타입스크립트는 MS사에서 만든 기존 자바스크립트에서 정적타입 문법을 추가한 개발언어입니다 타입스크립트는 매우 엄격한 정적 타입검사를 제공하는데 자바스크립트는 자료형을 동적타입 지향하기때문에 다른 자료형인 변수의 값도 할당할 수 있어 무결성 측면에서 큰 단점을 갖고 있었습니다 이 단점을 보완하고자 사용하는 것이 바로 타입스크립트입니다 프로젝트의 규모가 커질수록 유지보수성을 향상시켜 효율적으로 유지보수할 수 있는 큰 장점이 있습니다
자바스크립트와 문법적 차이
// 자바스크립트 기본 문법
const a = 1;
const b = true;
const c = "banana";
const d = [1,2,3];
//타입스크립트 문법
const a:number = 1;
const b:boolean = true;
const c:string = "banana"
const d:array = [1,2,3]
// 자바스크립트 문법
const func (a,b)=>{
return a+b;
}
//타입스크립트 문법
const func (a:number, b:number):number =>{
return a + b;
}
위 예제처럼 반드시 변수, 함수에는 자료형을 붙여줘야 합니다 자료형을 입력하지 않으면 오류가 출력되기 때문에 잘못된 입력으로 인하 버그나 오류를 줄일 수 있습니다
타입 종류📌
기본타입: string, number, boolean, null, nudefined 등
배열타입: number[], string[]
튜플 타입: [string, number]
열거형타입: enum
모든타입: any (비권장)
union타입: string | number (여러타입 사용시)
인터페이스 ( Interface )📌
인터페이스는 직접 자료형타입을 만들 수 있는 기능 객체의 구조를 정의하고 해당 객체가 가져야하는 속성과 타입을 명확히 지정할 수 있습니다
interface User {
name: string;
age: number;
isAdmin: boolean;
}
const user1: User = {
name: "Alice",
age: 25,
isAdmin: false
};
//잘못된 사용예제
const user2: User = {
name: "Bob",
age: 30,
isAdmin: true,
email: "bob@example.com" // 'email' 속성이 없으므로 오류 출력
};
그렇다면 함수에선 어떻게 사용할까요?
interface Product {
name: string;
price: number;
}
function showProduct(product: Product): string {
return `상품명: ${product.name}, 가격: ${product.price}원`;
}
const item = { name: "Laptop", price: 1200000 };
console.log(showProduct(item)); // 정상 출력!
만약 필수 속성이 아닌 값이 있을때는? 옵셔널 속성 사용!
interface Person {
name: string;
age?: number; // 선택적 속성 (있어도 되고 없어도 됨)
}
const p1: Person = { name: "Alice" };
const p2: Person = { name: "Bob", age: 30 }; // 둘 다 정상!
이렇게 속성명에 ?를 작성해주면 필수속성이 아닌 선택적 속성이 됩니다
이렇게 타입스크립트를 사용하면 좀 더 명확한 데이터 처리를 할 수 있고 잘못된 데이터가 입력되어 발생하는 버그를 최소화 할 수 있습니다 그리고 코드가 길어지거나 많아질때 객체지향 설계로 좀 더 나은 코드를 작성할 수 있습니다
interface Shape {
getArea(): number;
}
class Circle implements Shape {
radius: number;
constructor(radius: number) {
this.radius = radius;
}
getArea(): number {
return Math.PI * this.radius ** 2;
}
}
const myCircle = new Circle(10);
console.log(myCircle.getArea()); // 314.159.. 나옴!
클래스 사용법을 좀 더 알아봅시다!
클래스 접근 제한자📌
속성에 접근 제한 키워드를 붙여 속성에 대한 접근을 엄격하게 제한 할 수 있습니다
이렇게 작성하면 좀 더 무결성이 강화된 코드를 작성할 수 있어요!
class User {
public username: string; // 모든 곳에서 접근 가능!
private password: string; // 클래스 내부에서만 접근 가능!
constructor(username: string, password: string) {
this.username = username;
this.password = password;
}
public getUsername(): string {
return this.username;
}
private getPassword(): string {
return this.password; // 클래스 내부에서는 접근 가능!
}
}
const user1 = new User("apple", "applePass123");
console.log(user1.getUsername()); // 정상 출력: "apple"
// console.log(user1.password); // 오류: 'password'는 private 속성이므로 접근 불가능함!