npm i typescript -g
글로벌로 설치.
typescript 로 작성된 파일을 javascript 파일 형식으로 바꿔준다.
tsc 파일명.ts
프로젝트에는 설정 파일을 넣어줘야 한다.
tsc --init
tsconfig.json 이 생성된다.
이 안에 tsc 설정을 넣어줄 수 있다.
tsc 만 실행시키면 프로젝트 안에 ts 파일을 js 파일로 변경해준다.
tsc -w
: watch mode 설정으로 파일이 수정될 때 마다 자동으로 컴파일되도록 한다.
npm init -y
npm 설정 파일을 만들고
npm i typescript
프로젝트 안에 node_modules 안에 설치한다.
사용할 때는
node_modules/.bin/tsc
node_modules/typescript/.bin/tsc
npx tsc
중 편한것을 사용하면 된다.
프로젝트 전체를 컴파일할 수 있도록
npx tsc --init
let a: string; // type annotation 으로 type 설정
a = 'lee';
a = 39; //error
JavaScript : Dynamic Types
TypeScript : Static Types
&{expr}
과 같이 사용ECMAScript2015 의 symbol 이다.
new Symbol 로 사용할 수 없다.
Symbol 을 함수로 사용해서 symbol 타입을 만들어낼 수 있다.
primitive type 의 값을 담아서 사용한다.
고유하고 수정불가능한 값으로 만들어 준다.
주로 접근을 제어하는데 쓰는 경우가 많다.
const sym = Symbol();
const obj = { [sym]:"value", };
obj[sym]; // value
함수는 Symbol, 타입은 symbol
소문자만 존재한다.
null 은 null 값만 갖고, undefined 는 undefined 만 갖는다.
컴파일 옵션에서 '--strictNullChecks' 를 true 로 하면 null과 undefined는 void나 자기 자신들에게만 할당 할 수 있게 된다.( null과 undefined 를 할당할 수 있게 하려면, union type을 이용해야한다. )
let union : string | null = null;
합집합처럼 사용하면 된다. string 도 되고 null 도 된다는 의미.
// literal 방식으로 만들기
const person1 = {name:'lee', age:20};
// person1 is not "object" type
// person1 is "{name:string, age:number}" type
// 내장 전역객체 Object 를 사용하여 Object 만들기
const person2 = Object.create({name:'lee', age:20});
표현방법
let list : number[] = [1,2,3]; // 더 많이 사용함.
let list : Array<number> = [1,2,3]; // 충돌날 우려가 있음.
let list : number|string[] = [1,2,3,'4'];
// union 방식으로 사용, 모든 item이 number|string이 된다.
표현방법
// 배열 안에 타입 순서와 배열의 길이를 맞춰줘야한다.
// 길이가 맞지 않으면 undefined가 할당되어있다.
let x:[string, number];
x = ["hellw", 20];
//구조분해할당
const [first, second, third] = x;
// first:string, second:number, third:undefined
// 위치에 맞게 타입이 할당된다.
어떤 타입이어도 상관없는 타입
any를 최대한 쓰지 않도록 하는게 좋음
컴파일 타임에 타입 체크가 정상적으로 이뤄지지 않는다.
컴파일 옵션 중에는 any 를 써야하는데 쓰지 않으면 오류를 뱉도록 하는 옵션도 있다.(noImplicitAny)
any 는 객체를 통해 전파된다.
any 사용으로 인한 편의는 안정성을 잃는 대가로 돌아온다.
타입 안정성은 typeScript 를 사용하는 주요 동기이기 때문에 필요한 경우 외에는 any의 사용을 피해야 한다.
let looselyTyped: any = {};
const d = looselyTyped.a.b.c.d; // any
any가 계속 전파되는 것을 막아줘야한다. (leaking)
중간에 number가 들어오면 number type 이 되도록 하는 방식.
// 타입만 지정하는 declare 사용
declare const maybe: unknown;
const aNumber: number = maybe;
// typeGuard
if(maybe===true){
const aBoolean: boolean = maybe;
const aString:string = maybe;
}
if(typeof maybe === 'string'){
const aString:string = maybe;
}
function error(message: string): never {
throw new Error(message);
}
// never type 이 된다.
function fail() {
return error("failed");
}
function infiniteLoop(): never {
while(true) {};
}
let a: string = "hello";
if(typeof a !== "string"){
a; // never type
}
// generic type (type 변수)
type Indexable<T> = T extends string ? T & {[index:string]: any} : never;
type ObjectIndexable = Indexable<{}>; // never
interface PersonInterface {
name: string;
age: number;
}
type PersonTypeAlias = {
name: string;
age: number;
};
function f8(a: PersonInterface): string {
return `이름은 ${a.name} 이고, 연령대는 ${Math.floor(a.age/10)*10}대 입니다.`;
}
TypeScript 는 Structural Type 이다.
같거나 서브 타입인 경우, 할당이 가능하다. => 공변(포함관계 하위로)
함수의 매개변수가 타입만 같거나 슈퍼타입(인 경우, 할당이 가능하다. => 반변(포함관계 상위로)
: strictFunctionTypes 옵션을 켜면 함수의 매개변수가 반변에 해당하지 않을 경우 에러를 통해 경고한다.
compile 하기위한 설정 및 옵션은 config에 있다.
config를 잘 알아야 typeScript를 잘 사용할 수 있다.
compileOnSave
extends
compileOptions ***
files
include
exclude
references
...
: true 로 설정하면 save 하면 compile 한다.
: tsconfig를 상속하여 사용한다.
github.com/tsconfig/bases
extends 할 설정들이 있다.
: 셋다 설정이 없으면 전부 컴파일
glob 패턴 (.gitignore)
include ( exclude 보다 약함, * 같은걸 사용하면, .ts/tsx/d.ts 만 include(allowJS)
exclude ( 설정안하면- node_modules, bower_components, jspm_packages,outdir 은 default로 제외 ) ( outdir은 항상 제외한다.include에 있어도 제외)
: 내보내는 파일 형태 설정
: 컴파일된 파일을 저장하는 폴더 생성 설정
: 컴파일할 폴더 지정, 지정하지 않으면 컴파일할 파일의 가장 상위가 설정된다.
strict type checking options ( 엄격하게 타입을 체크할 옵션들 내장하고 있다.)
options
--noImplicitAny
--noImplicitThis
--strictNullChecks
--strictFunctionTypes
--strictPropertyInitialization
--strictBindCallApply
--alwaysStrict
strict 를 true로 하고 사용해야한다. 필수 옵션!