TypeScript
자바스크립트 변수 / 매개변수 / 리턴 값에 타입을 부여한 확장된 언어이다.
- 타입스크립트 >= 자바스크립트 타스는 자스의 Superset이다.
- 에러의 사전 방지와 IDE의 자동 완성 기능을 적극 활용하여 생산성이 높아진다.
- 자바스크립트와는 다르게 브라우저에서 실행하기 위해 컴파일 과정을 거쳐야 한다.
기본 타입
string
- 문자일 경우 사용한다.
const city: string = "Seoul";
number
- 수일 경우 사용한다.
const age: number = 29;
boolean
- true / false
const flag: boolean = false;
null
- null일 경우 사용한다.
const n: null = null;
undefined
- undefined일 경우 사용한다.
const u: undefined = undefined;
object
- 객체일 경우 사용한다.
const person: {
name: string,
age: number,
address: string,
} = {
name: "라이언 달",
age: 29,
address: "Texas",
}
// 속성이 나중에 추가될 경우
const person: {
name: string,
age: number,
address: string,
grade?: string,
} = {
name: "라이언 달",
age: 29,
address: "Texas",
}
Array
- 요소의 타입과 개수가 고정된 배열이다.
- 모든 요소들의 타입이 모두 같을 필요는 없다.
// 문자 배열
const strArr: string[] = ["강북구", "강남구", "강서구", "강동구"];
const strArr: Array<string> = ["강북구", "강남구", "강서구", "강동구"];
// 수 배열
const numArr: number[] = [9, 4, 1, 1, 0, 3];
// 제네릭 타입 사용
const numArr: Array<number> = [9, 4, 1, 1, 0, 3];
// string number boolean
const arr: (string | number | boolean) = [941103, "배열", false];
// 배열에 특정 값 지정
const arr: ["보스", "마샬", "스피커"] = ["보스", "마샬", "스피커"];
// 배열을 값이 변하지 않는 상수처럼 사용 as const (readonly)
const absoluteArray = ["javaScript", "TypeScript", "Node.js"] as const;
- 읽기 전용 배열을 통해 값을 바꿀 수 없는 배열을 만들 수 있다.
const readonlyArr: ReadonlyArray<string | number> = ["문자열", "수"];
Tuple
- 길이가 고정되고 타입이 지정돼있는 배열의 형식이다.
- 튜플로 선언 한 배열에 push는 가능하다.
const arr: [number, boolean, boolean] = [941103, false, true];
const arr: [string, number, Array<string>] = ["Tuple", 941103, ["Tuple"]];
// 오류
arr[3]
enum
- 특정 값(상수)들의 집합이다.
- 문자와 수를 혼합하여 만들 수 있지만 가급적 같은 타입으로 이루어진 이넘을 사용해야 한다.
enum Color { green, yellow, white }
const personalColor = Color.yellow;
enum brand = {
nike,
adidas,
newbalance,
}
const myBrand = brand.nike; // 0;
enum brand = {
nike = "나이키",
adidas = "아디다스",
newbalance = "뉴발란스",
}
const myBrand = brand.adidas; // 아디다스
enum Direction {
Up = 1,
Down,
Left,
Right,
}
const upScroll = Direction.Up; // 1
any
- 모든 타입이 들어갈 수 있다.
- 주로 사용자로부터 받은 데이터나 서드 파티 라이브러리 같은 콘텐츠에서 사용한다.
const anytime: any = "플레이그라운드"
const anytime: any = ["getFullYear", "getHours", "getSeconds"];
void
- 변수에 undefined/null 함수에 리턴 값이 없을 경우 지정한다.
const checking: void = undefined;
function logging(): void {
console.log("here");
}
never
- 함수 끝에 절대 도달하지 않는다는 의미이다.
- 보통 논리적으로 말이 안 되는 경우 에러로 만난다.
const arr: [] = [];
function never(): never {
while (true) {
}
}
'언어 > 타입스크립트' 카테고리의 다른 글
TypeScript 유틸리티 타입 (0) | 2022.05.29 |
---|---|
TypeScript 타입 가드 (0) | 2022.05.28 |
TypeScript 제네릭 (0) | 2022.05.24 |
TypeScript 인터페이스 타입 (0) | 2022.05.23 |
TypeScript 함수 (0) | 2022.05.21 |