JavaScript 슈퍼셋으로, JavaScript에 정적 타입을 추가한 프로그래밍 언어다.
자바스크립트는 런타임에 변수의 타입이 결정된다.
타입스크립트는 컴파일타임에 타입을 검사한다.
자바스크립트는 브라우저에서 직접 실행된다.
타입스크립트는 자바스크립트로 트랜스파일한 후 브라우저에서 실행된다.
interface Person { name: String };
const alice: Person = { name: 'Alice' };
const alice: Person = {};
// 'Person' 유형에 필요한 'name' 속성이 '{}' 유형에 없습니다.
잉여 속성 체크란?
타입에 선언된 속성 외에 속성이 있는지 체크하는 것
타입 단언이 꼭 필요한 경우가 아니라면, 안정성 체크도 되는 타입 선언을 사용하는 것이 좋다
const bob = { name: 'Bob' } as Person;
타입스트립트가 추론한 타입이 있더라도 Person 타입으로 간주
강제로 타입 지정
→ 타입 체커에서 오류를 무시하라고 하는 것
const bob = {} as Person; // 오류 없음
타입 체커가 추론한 타입보다 개발자가 판단하는 타입이 더 정확할 때
타입스크립트는 DOM에 접근할 수 없다.
document.querySelector('#myBtn').addEventListener('click', e => {
e.currentTarget; // EventTarget
const button = e.currentTarget as HTMLButtonElement;
});
const el = document.getElementById('foo')!;
→ 접미사로 쓰인 !는 그 값이 null(혹이 undefined)이 아니라는 단언문으로 해석된다
리터럴 타입이란?
값 자체가 타입
const str = 'hello';
// const str: "hello"
각 요소 자리에 타입이 고정되어 있는 배열
function getText<T>(text: T): T {
const a: T = ''
return text;
}
getText<string>(10);
getText<number>(10);
getText<boolean>(true);
추상 클래스
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log("이동 중...");
}
}
class Dog extends Animal {
makeSound(): void {
console.log("멍멍");
}
}
const dog = new Dog();
dog.makeSound(); // 멍멍
dog.move(); // 이동 중...
값을 읽어서 타입을 반환한다
const person = {
name: "Alice",
age: 30
};
type PersonType = typeof person;
// type PersonType = {
// name: string;
// age: number;
// }
typeof와 함께 객체의 프로퍼티 key들을 유니온 타입으로 지정하기 위해 사용했다
const designToken = {
scale: {
xxs: 2,
xs: 4,
s: 8,
m: 12,
base: 16,
l: 24,
xl: 32,
xxl: 40,
xxxl: 48
}
};
type Scale = keyof typeof designToken.scale;
리액트는 자체 타입스크립트 지원이 없다.
커뮤니티 타입 @types/react를 설치해야 한다.
리액트 타입 정의에서 CommonJS모듈 시스템을 따른다.
// node_modules/@types/react/index.d.ts
export = React;
따라서 ECMAScript 모듈 시스템과의 호환성을 위해 tsconfig 파일에 아래와 같이 설정한다.
{
"compilerOptions": {
"esModuleInterop": true,
}
}