Typescript는 JavaScript에 정적 타입 시스템(static type system) 을 추가한 프로그래밍 언어로 , JavaScript의 확장된 버전입니다. TypeScript는 개발자에게 코드 작성 중에 더 많은 안전성과 가독성을 제공하며, 대규모 프로젝트에서의 유지보수를 향상 시킬 수 있습니다.
타입 계층도
- 기본 타입 (Primitive type): string,number, boolean, symbol, enum, 문자열 리터
- 객체 타입 : Array, tuple, class , interface, function, constructor
- 기타: union, intersection
1. 변수 선언
let variableName : dataType = value;
ex)
let message : string = "Hello TypeScript"
let number : number = "123456"
let trueFalse : boolean = false
2. 함수 선언
function add(x: number, y: number): number {
return x + y;
}
3. 인터페이스 (interface)
인터페이스를 사용하여 객체 형태를 정의 할 수 있다.
interface Person {
name: string;
age: number;
}
let person: Person = {
name: "Sang",
age: 30
};
4. 배열
let numbers: number[] = [1,2,3,4];
let strings = Array<string> = ["a", "b", "c", "d"];
let arr1: Array<number> = [10 , 20, 30];
let arr2: [string, number] = ["sang", 30];
let falseTrue: boolean = true;
5. 조건문
if(condition){
// 코드 블록
} else {
// 다른 코드 블록
}
6. 반복문
for(let i = 0; i < 5; i++) {
// 반복할 코드
}
while (condition) {
// 조건이 참일 때 실행할 코드
}
7. 클래스
class Person {
private name : string;
constructor(name: string){
this.name = name
}
greet(): string {
return `hello, ${this,name}`;
}
}
let person = new Person("Alice");
console.log(person.great());
8. 타입 별칭 (Type Aliases)
type Point = {
x : number;
y: number;
};
let point: Point = { x: 10, y:20 };
9. Enum
열거형 (Enums) 으로 이름이 있는 상수들의 집합을 정의 할 수 있습니다. 열거형을 사용하면 의도를 문서화 하거나 구분되는 사례 집합을 더 쉽게 만들수 있습니다. TypeScript는 숫자와 문자열-기반 열거형을 제공합니다.
*enum 키워드를 사용하면 default 값을 선언 할 수 있다.
// 숫자형
enum Shoes {
Nike, // 0
Adidas, // 1
NewBalance // 2
}
const myShoes = Shoes.Nike; // 0
// 문자형
enum Person {
park = "박",
kim = "김"
}
const person = Person.kim; // 김
'TypeScript' 카테고리의 다른 글
TypeScript 인터페이스 (0) | 2024.02.20 |
---|---|
TypeScript 제네릭(Generics) (0) | 2024.02.07 |