// JavaScript
function add(n1, n2){
if (typeof n1 !== 'number' || typeof n2 !== 'number'){
throw new Error('Incorrect input!');
}
return n1+n2;
}
const result = add(39, 28);
// TypeScript
function add(n1: number, n2:number){
return n1+n2;
}
const result = add(39,28);
let a = 'Mark';
a = 39; // 불가능(변수 a의 type이 string으로 자동 지정되어서)
let b; // type은 any
let c: string; // type을 string으로 선언 -> Type Annotation
function hello(d: number){} // 매개변수에도 가능
hello(30); // 가능
hello('Loopy'); // 불가능
Node.js(https://nodejs.org/en/) + NVM (https://github.com/coreybutler/nvm-windows)
$ npm i typescript -g
typescript 설치 (global)
(여기서 -g 없이 설치하면 이후에 $ npx tsc
형태로 사용)
$ tsc --init
tsconfig.json 생성
$ tsc test.ts
해당 파일에 ts compiler 적용
$ tsc
전체 파일에 ts compiler 적용
$ tsc -w
watch 모드 -> 변경사항 발생할 때 마다 자동으로 컴파일러 적용
new Boolean(false);
래퍼 객체로 생성되어 object type이므로 권장X (그냥 let a = false;
로 사용하기)0xf00d
, binary(2) 0b1010
, octal(8) 0o744
["ES2015", "DOM"]
추가 후 사용Symbol()
타입으로는 symbol
Symbol('foo') === Symbol('foo') // false
--strictNullChecks
옵션: null과 undefined도 자신에게만 할당 가능 (예외로 void에 undefined는 무조건 가능)let u: string | null = null;
{}
필수let li = [1,2,3];
let li: number[] = [1,2,3];
let li: Array<number> = [1,2,3];
let li: (number | string)[] = [1,2,3,'가'];
let x: [string, number];
순서, 타입, 길이 전부 맞아야 함const maybe: unknown;
if (typeof maybe === "string") { // typeof 타입 가드
const aString: string = maybe;
}
if ...
function err(message: string): never{
throw new Error(message);
}