타입스크립트 스터디를 하게된 기념으로 타입스크립트를 다시 정리해 볼까 한다.
그 시작은 기본 타입으로 정했다.
현재 개인적인 타입스크립트 공부는 캡틴판교님의 인프런 강의로 진행하고 있다.
각 선언 방식은 아래와 같다.
const str: string = 'hello world';
const num: number = 1;
const boo: boolean = true;
TypeScirpt에서 배열을 선언하는 방식은 두 가지가 있다.
number[]
방식 (배열 모양의 바로 앞에 안의 요소들의 타입을 정의하는 방식)const arr1: number[] = [1, 2, 3];
const arr2: string[] = ['hello', 'world'];
Array<number>
방식 (제네릭을 사용하는 방식)const arr1: Array<number> = [1, 2, 3];
const arr2: Array<string> = ['hello', 'world'];
방식만 다를 뿐이지 위와 같다.
특이한 점은 Array
같이 첫 문자를 대문자로 써줘야한다.
[number]
이라고 헷깔릴 수도 있는데 이는 배열이 아니라 튜플이다.
자바스크립트에는 존재하지 않는 타입으로 길이와 타입이 고정된 배열이다.
만약 길이는 2이고 첫 번째 인자는 number
두 번째 인자는 string
으로 이루어진 배열을 생성하고 싶다면, 다음과 같이 선언하면 된다.
const arr: [number, string] = [1, 'hello'];
객체는 단순하게 object
라고 선언하면 된다.
const obj: object = {};
만약 key
마다 타입을 정하고 싶으면 아래와 같이 선언하면 된다.
const game: { title: string, playtime: number } = {
title: 'superMario',
playtime: 20
};
key
에 대한 타입임으로 아래와 같이 순서를 바꿔도 된다.
const game: { title: string, playtime: number } = {
playtime: 20,
title: 'superMario'
};
Any는 단어 그대로 모든 타입에 대해서 허용한다는 의미를 갖고 있다.
const str: any = 'hello';
const num: any = 10;
const arr: any = ['a', 2, true];
변수에는 undefined
와 null
만 할당하고, 함수에는 반환 값을 설정할 수 없는 타입이다.
void
는 자바스크립트에는 없는 키워드로, 함수에 ‘이 함수는 아무것도 반환하지 않는다.’ 라는 의미를 부여한다.
const unuseful: void = undefined;
function notuse(): void {
console.log('notReturn');
}
let foo: never = 123; // Error: Type number is not assignable to never
위 예시는 never
타입엔 다른 타입이 할당 될 수 없음을 알려주고 있다.
let foo: never;
let goo: any = 123;
foo = goo // Error
// 이 함수는 절대 함수의 끝까지 실행되지 않는다는 의미
function neverEnd(): never {
while (true) {
}
}