타입 시스템
- 컴파일러에게 사용하는 타입을 명시적으로 지정 ; TS에 해당
- 컴파일러가 자동으로 타입을 추론 ; JS에 해당 -> 사용법에 대한 오해 야기 => 비추
- TS의 경우 매게변수에도, return값에도 명확하게 type을 명시해줘야함.
function f5(a:number):number{
if(a>0){
return a*38;
}
}
function f7(a:{name:string; age:number}):string{
return `이름은 ${a.name}이고, 연령대는${
Math.floor(a.age/10)*10
}대 입니다.`;
}
console.log(f7({name:'Mark',age:23}));
console.log(f7('Mark')); // 오류 발생
Type 호환성
공변
; 같거나 서브 타입인 경우 할당 가능
let sub1:number=1;
let sup1:any=sub1;
sub1=sup1; //any는 number의 하위버전이기 때문에 오류 x 아래 코드들도 동일
let sub2:string='';
let sup2:string|number=sub2;
let sub3:{a:string; b:number}={a:'',b:1};
let sup3:{a:string|number;b:number}=sub3;
let sub4:Array<{a:string;b:number}> = [{a:'',b:1}];
let sup4:Array<{a:string|number; b:number}> = sub4;
반병
; 함수의 매개변수 타입만 같거나 슈퍼타입인 경우 할당 가능
class Person{}
class Developer1 extends Person{
coding(){}
}
class Developer2 extends Person{
burning(){}
}
function tellme(f:(d:Developer1)=>Developer1){}
tellme(function dToD(d:Developer1):Developer1{
return new Developer1();
});
tellme(function pTod(d:Person):Developer1{
return new Developer1();
});
tellme(function sToD(d:Developer2):Developer1{ // (d: Developer2) => Developer1' 형식의 인수는 '(d: Developer1) => Developer1' 형식의 매개 변수에 할당될 수 없습니다
return new Developer1();
});
Compilation Context
TSconfig Schema
'tsconfig.json' 파일
1. CompileOnSave
- true / false(기본값)
2. extends
- 파일 경로명 ; string
3. files, include, exclude
- 셋다 설정이 없다면, 전부다 컴파일
file ; 상대 혹은 절대 경로의 리스트 배열
- exclude보다 쎔
include ; glob 패턴(마치 .gitignore)
- exclude보다 약함
- *같은걸 사용하면 .ts/.tsx/.d.ts만 include
exclude
- 설정 안하면 4가지(node_modules,bower_componets,jspm_packages,<outDir>)를 default으로 제외
- <outDir>은 항상 제외
4. CompileOptions
TypeRoots ; 내장 type definition 시스템.
- 아무설정 x -> node_modules/@types라는 모든 경로를 찾아서 사용
- 배열 안에 들어있는 경로들 아래서만 가져옴
Types ; 배열 안의 모듈 혹은 ./node_moudles/@types/ 안의 모듈 이름에서 찾아옴
- TypeRoots와 Types를 같이 사용하지 않음
target ; 빌드의 결과물을 어떤 버전으로 할 것이냐. 미지정 시 es3
lib ; 기본 type definition 라이브러리를 어떤 것을 사용할 것이냐
outDir ; 출력할 파일 설정
outFile ; 단일파일로 출력시 파일명
rootDir ; 입력파일의 rootDir 설정
strict ; 무조건 true 설정할 것
- nolmplicitAny ; 타입을 명시적으로 지정하지 않은 경우 TS 추론 중 any라 판단되면 컴파일 에러 발생
- noImplicitThis ; 명시적이지 않게 any타입을 사용하여, this 표현식에 사용하면 에러 발생
- strictNullChecks ; 모든 타입에 자동으로 포함되어 있는 'null', 'undefined' 제거
- strictFunctionTypes
- strictPropertyInitialization
- strictBindCallApply ; bind, call, apply에 대한 더 엄격한 검사 수행
- noImplicitReturns ; 함수 내에서 모든 코드가 값을 리턴하지 않으면, 컴파일 에러
- alwaysStrict ; 각 소스 파일에 대해 JavaScript의 strict mode로 코드를 분석하고, "엄격하게 사용"을 해제
'WebProgramming > JS' 카테고리의 다른 글
[JavaScript] Object Methods(assign,keys,values,entries,fromEntries) (0) | 2022.07.26 |
---|---|
[JS] Array 메소드 (map,filter,reduce,find,concat,slice) (0) | 2022.07.15 |
[JS] JS 라이브러리 (lodash, axios) (0) | 2022.06.30 |
[TS] 타입 별칭 & Interface (0) | 2022.06.24 |
[TS] TypeSCript이란? & 타입 (0) | 2022.06.12 |
[JS] JSON (0) | 2022.06.11 |
[JS] 정규표현식 (0) | 2022.06.11 |
[JS] import,export ; 모듈 가져오기,내보내기 (0) | 2022.06.11 |