타입스크립트를 도입하는 이유
버그를 줄이고 -> 쉬운 유지보수 -> 질좋은 코드
타입스크립트 특징
function add (a: number, b: number){
return a+b;
}
console.log(add('3','5')); -> 타입 에러!
객체지향적
class, interface, constructor, public, private
컴파일 타임 오류
컴파일? -> 어떤 언어의 코드를 다른 언어로 바꿔주는 변환과정!
자바스크립트만 이해할 수 있는 브라우저는 타입스크립트를 그대로 이해하지 못함 -> 타입스크립트를 자바스크립트로 컴파일 ->
tsc(TypeScript Compiler) 명령어로 타입스크립트 -> 자바스크립트 컴파일 가능!
터미널 - tsc 파일명.확장자
tsc --init -> tsconfig.json파일 생성!
tsconfig.json파일
설정파일
tsc -w 파일명.확장자 -> watch모드, 타입스크립트 코드를 수정할때마다 매번 tsc 파일명.확장자 의 번거로움을 해결! 코드가 수정되면 자동으로 감시하여 컴파일한다.
타입추론
let a = 5;
a = 'hello'
=> 타입스크립트에서는 에러! -> a를 number로 타입추론 했기때문에 number타입 변수에 문자열을 대입하면 에러!
타입명시
let x:string = '문자열';
number, string, boolean, void, object, any
interface 이름(대문자로 시작) {
변수명 : 타입;
}
interface Student {
studentID: number;
studentName: string;
age: number;
gender: string;
subject: string;
addComment (comment: string): string;
addComment: (comment: string) => string;
}
:Student 처럼 사용가능!
? 선택적 프로퍼티
interface Student {
studentID: number;
studentName: string;
age?: number;
gender: string;
subject: string;
}
-> age값은 있어도 되고, 없어도 되고!
readonly
읽기전용 프로퍼티, 객체 생성시 할당된 프로퍼티의 값을 바꿀 수 없다!
const과 비슷한 개념이라고 생각하면 될듯!
interface Student {
readonly studentID: number;
studentName: string;
age: number;
gender: string;
subject: string;
addComment (comment: string): string;
addComment: (comment: string) => string;
}