TypeScript란
정적 타이핑을 추가한 JavaScript 구문
❓ 사용해야하는 이유
JavaScript에서는 어떤 유형의 데이터가 전달되는지 이해하기 어렵기 때문에 개발자는 설명서나 구현 내용을 보면서 추측해야 함.
➡️ TypeScript를 통해 코드 내에서 전달되는 데이터 유형을 지정할 수 있고, 유형이 일치하지 않을 때의 오류를 발견할 수 있음.
TypeScript 시작하기
컴파일러 설치
npm install typescript --save -dev
npx tsc --init // 컴파일러 옵션 설정 파일 생성
- 생성된 tsconfig.json 파일 수정
{
"include": ["src"], // 컴파일러가 src 디렉토리에 있는 ts 파일을 js 파일로 변환하여
"compilerOptions": {
"outDir": "./build", // build 디렉토리에 저장
}
}
- 컴파일 수행
npx tsc
TypeScript 유형
명시적 유형
let firstName: string = "Dylan";
암시적 유형
let firstName = "Dylan"; // 할당된 값을 기반으로 유형 "추측"
할당 오류
let firstName: string = "Dylan";
firstName = 33; // 타입 에러
console.log(firstName);
추론 불가
const json = JSON.parse("55");
console.log(typeof json); // 타입 추론 불가, number 타입으로 인식
특수 유형
- any: 모든 유형이 사용될 수 있도록 하는 유형, 권장 X
let v: any = true;
v = "string";
Math.round(v);
- unknown: any와 비슷하며 안전한 유형, 유형을 모를 때 사용
let w: unknown = 1;
w = "string";
console.log(w);
- never: 할당 시 오류 발생, 거의 사용되진 않지만 고급 제네릭에 사용
let x: never;
let x: never = true; // 할당 불가
배열
const names: string[] = [];
names.push("Dylan");
console.log(names);
// 읽기 전용
const names2: readonly string[] = ["Dylan"];
names2.push("Jack"); // Error, 변경 불가
튜플
각 인덱스에 대해 길이와 유형이 미리 정의된 형식화된 배열
let ourTuple: [number, boolean, string];
ourTuple = [5, false, "Coding"];
console.log(ourTuple);
객체
const car1: { type: string; model: string; year: number } = {
type: "Toyota",
model: "Corolla",
year: 20009,
};
console.log(car1);
// 선택 속성
const car2: { type: string; mileage?: number } = {
type: "Toyota",
};
car2.mileage = 2000;
console.log(car2);
// 동적 프로퍼티 네이밍
const nameAgeMap: { [index: string]: number } = {};
nameAgeMap.Jack = 25;
console.log(nameAgeMap);
Enum(열거형)
상수 그룹을 나타내는 특수한 "클래스"
enum CardinalDirections {
North,
East,
South,
West,
}
console.log(CardinalDirections);
Type과 Interface
- 별칭으로 유형을 정의
Type
type Rectangle1 = {
height: number;
width: number;
};
const rectangle1: Rectangle1 = {
height: 20,
width: 10,
};
console.log(rectangle1);
Interface
- Type과 비슷하지만 객체 유형에만 적용
interface Rectangle2 {
height: number;
width: number;
}
const rectangle2: Rectangle2 = {
height: 20,
width: 10,
};
console.log(rectangle2);
Interface 확장(상속)
interface ColoredRectangle extends Rectangle2 {
color: string;
}
const coloredRectangle: ColoredRectangle = {
height: 20,
width: 10,
color: "red",
};
console.log(coloredRectangle);
Union
두 가지 이상의 유형일 수 있는 경우에 사용
function printStatusCode(code: string | number) {
console.log(`Status Code: ${code}`);
}
printStatusCode("404");
printStatusCode(200);
함수
function getTime(): number {
return new Date().getTime();
}
console.log(getTime());
디폴트 매개변수
function pow(value: number, exponent: number = 10) {
return value ** exponent;
}
console.log(pow(2));
명명된 매개변수
function divide({ dividend, divisor }: { dividend: number; divisor: number }) {
return dividend / divisor;
}
console.log(divide({ dividend: 10, divisor: 2 }));
나머지 매개변수
function add(a: number, b: number, ...rest: number[]) {
// ... 연산자는 낱개로 들어오는 값을 배열로 합쳐서 처리
return a + b + rest.reduce((p, c) => p + c, 0);
}
console.log(add(1, 2, 3, 4));
타입 별칭
type Negate = (value: number) => number;
const negateFunction: Negate = (value) => value * -1;
console.log(negateFunction(5));
Casting
변수의 유형을 재정의하는 과정
as 캐스팅
let a: unknown = "hello";
console.log((a as string).length);
<> 캐스팅
let b: unknown = "hi";
console.log((<string>b).length);
클래스
class Person {
private name: string;
public constructor(name: string) {
this.name = name;
}
public getName(): string {
return this.name;
}
}
const person = new Person("Jane");
console.log(person.getName());
728x90
반응형
'LG 유플러스 유레카 SW > TypeScript' 카테고리의 다른 글
[ #8] TypeScript 익히기(2) (0) | 2025.02.06 |
---|