Javascript + Type
말 그대로 기존의 Javascript에 정적 Type을 명시할 수 있도록 제작된 언어
델파이와 C#의 개발을 주도한 Anders Hejisberg가 개발에 참여하고 있어,
일부 기능이나 문법이 C#과 유사하다.
/* Javascript */
const a = 3;
const b = '5';
console.log( a * b ); // 15
/* Typescript */
const a: number = 3;
const b: string = '5';
console.log( a * b ); // compile error!!!
npm install -g typescript
tsc <filename>
Generic : class Stack<T> {}
Abstract Class : abstract class Node {}
Interface : interface Node {}
Decorator
function firstDecorator( target, name ) {
console.log('firstDecorator');
}
class Person {
@firstDecorator
job = 'programmer';
}
const p = new Person();
console.log( p.job );
// firstDecorator
// programmer
기존의 JS 코드를 변경하지 않고 typescript로 정의할 수 있게 해주는 파일
/* some-js-library.d.ts */
declare module "some-js-library" {
function someFunction(a: string, b: string): void;
class SomeClass {
/* ... */
}
}
/* index.ts */
import { someFunction, SomeClass } from "some-js-library";
런타임에는 약타입
ts-node
를 이용해 디버깅을 할 경우, 클라이언트가 잘못된 type을 넘겨주었을 때 typeerror를 잡아주지만,
실제 운영환경에서는 typescript를 컴파일한 js 파일이 실행이 되므로, 잘못된 type이 넘어와도 검사하지 않는다.
그래서 type guard 함수를 직접 작성하거나, io-ts
, runtypes
등의 라이브러리를 사용해 자료형 검사를 따로 실시해주어야 한다.
/* Number Type */
let value: number = 10;
console.log( typeof value ); // number
console.log( value.length ); // compile error!
value = [1, 2, 3, 4]; // compile error!
/* Any Type */
let value2: any = 10;
console.log( typeof value2 ); // number
console.log( value2.length ); // undefined. but running
value2 = [1, 2, 3, 4]; // ok
console.log( typeof value2 ); // object
console.log( value2.length ); // 4
/* Unknown Type */
let value3: unknown = 10;
console.log( typeof value3 ); // number
console.log( value3.length ); // compile error!
value3 = [1, 2, 3, 4]; // ok
console.log( typeof value3 ); // object
console.log( value3.length ); // 4
Any Type
Unknown Type