TypeScript 정적 타이핑
#1 타입 선언
// 변수 foo는 string 타입이다
let foo: string = 'hello';
TypeScript는 ES5, ES6의 상위 집합이므로 자바스크립트의 타입을 그대로 사용할 수 있으며 자바스트립트 타입 외에도 TypeScript 고유의 타입이 추가로 제공된다.
다양한 타입을 선언하는 방법은 아래와 같다.
// boolean
let isDone: boolean = false;
// null
let n: null = null;
// undefined
let u: undefined = undefined;
// number
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
// string
let color: string = 'blue';
color = 'red';
let myName: string = 'Lee'; // ES6 템플릿 문자열
let greeting: string = `Hello, my name is ${myName}.`; // ES6 템플릿 대입문
// object
const obj: object = {};
// array
let list1: any[] = [1, 'two', true];
let list2: number[] = [1, 2, 3];
let list3: Array<number> = [1, 2, 3]; // 제네릭 배열 타입
/*
tuple : 고정된 요소 수만큼의 타입을 미리 선언 후 배열을 표현
첫 번째 요소는 string 타입이고 두 번째 요소는 number 타입
*/
let tuple: [string, numebr];
tuple = ['hello', 10]; // OK
tuple = [10, 'hello']; // Error
tuple = ['hello', 10, 'world', 100]; // Error
tuple.push(true); // Error
// enum : 열거형은 숫자 값 집합에 이름을 지정한 것이다
enum Color1 { Red, Green, Blue };
let c1: Color1 = Color1.Green;
console.log(c1); // 1
enum Color2 { Red = 1, Green, Blue };
let c2: Color2 = Color2.Green;
console.log(c2); // 2
enum Color3 { Red = 1, Green = 2, Blue = 4 };
let c3: Color3 = Color3.Blue;
console.log(c3); // 4
/*
any : 타입 추론을 할 수 없거나 타입 체크가 필요 없는 변수에 사용한다
var 키워드로 선언한 변수와 같이 어떤 타입의 값이라도 할당할 수 있다
*/
let notSure: any = 4;
notSure = 'maby a string instead';
notSure = false; // okay, definitely a boolean
// void : 일반적으로 함수에서 반환값이 없을 떄 사용한다
function warnUser(): void {
console.log("This is my warning message");
}
// never : 결코 발생하지 않는 값
function infiniteLoop(): never {
while (true) {}
}
function error(message: string): never {
throw new Error(message);
}
타입은 대소문자를 구별하므로 주의가 필요하다.
#2 정적 타이핑
var foo;
console.log(typeof foo); // undefined
foo = null;
console.log(typeof foo); // object
foo = {};
console.log(typeof foo); // object
foo = 3;
console.log(typeof foo); // number
foo = 3.14;
console.log(typeof foo); // number
foo = "Hi there";
console.log(typeof foo); // string
foo = true;
console.log(typeof foo); // boolean
TypeScript의 가장 독특한 특징은 정적 타이핑을 지원한다는 것이다.
정적 타입 언어는 타입을 명시적으로 선언하며, 타입이 결정된 후에는 타입을 변경할 수 없다.
잘못된 타입의 값이 할당 또는 반환되면 컴파일러는 이를 감지해 에러를 발생시킨다.
let boo: string, // 문지열 타입
woo: number, // 숫자 타입
goo: boolean; // 불리언 타입
boo = 'Hello';
woo = 123;
goo = 'true'; // error : Type '"true"' is not assignable to type 'boolean'
정적 타이핑은 변수는 물론 함수의 매개변수와 반환값에도 사용이 가능하다.
function add(x: number, y: number) {
return x + y;
}
console.log(add(10, 10)); // 20
console.log(add('10', '10'));
// error TS2345 Argument of type '"10"' is not assignable to parameter of type 'number'
정적 타이핑의 장점은 코드 가독성, 예측설, 안정성이라고 볼 수 있는데 이는 대규모 프로젝트에 매우 적합하다.
#3 타입 추론
let foo = 123; // foo는 number 타입
위 코드를 보면 변수 foo에 타입을 선언하지 않았으나 타입 추론에 의해 변수의 타입이 결정된다.
동적 타입 언어는 타입 추론에 의해 변수의 타입이 결정된 후에도 같은 변수에 여러 타입의 값을 교차하여 할당할 수 있다.
하지만 정적 타입 언어는 타입이 결정된 후에는 타입을 변경할 수 없다. TypeScript는 정적 타입 언어이므로 타입 추론으로 타입이 결정된 이후, 다른 타입의 값을 할당하면
에러가 발생한다.
let boo = 123; // boo는 number 타입
boo = 'hi'; // error : Type '"hi"' is not assignable to type 'number'
타입 선언을 생략하고 값도 할당하지 않아서 타입을 추론할 수 없으면 any 타입이 된다.
any 타입의 변수는 자바스크립트의 var 키워드로 선언한 변수처럼 어떤 타입의 값도 재할당이 가능하다.
이는 TypeScript를 사용하는 장점을 없애기 때문에 사용하지 않는 편이 좋다.
let zoo; // = let zoo: any
zoo = 'hello';
console.log(typeof zoo); // string
zoo = 'true';
console.log(typeof zoo); // boolean
'TypeScript' 카테고리의 다른 글
제네릭 (0) | 2019.08.28 |
---|---|
인터페이스 (0) | 2019.08.27 |
클래스 (0) | 2019.08.26 |
TypeScript??? (0) | 2019.08.24 |