타입
은 자바스크립트에서 다루는 값의 형태null //null
undefined //undefined
true // boolean
"types" //string
1217 //number
1217n //bigint
Symbol("bmk"); //symbol
//타입 : string
let bestSong = Math.random() > 0.5
? "Chain of Fools"
: "Respect";
타입 시스템의 기본적인 작동 방식
- 코드를 읽고 존재하는 모든 타입과 값을 이해한다.
- 각 값이 초기 선언에서 가질 수 있는 타입을 확인한다.
- 각 값이 추후 코드에서 어떻게 사용될 수 있는지 모든 방법을 확인한다.
- 값의 사용법이 타입과 일치하지 않으면 사용자에게 오류를 표시한다.
let firstName ="Jade"
firstName.length()
//Errors: This expression is not callable.
// Type 'Number' has no call signatures.
let let wat;
//Error: ',' expected.
타입스크립트는 구문 오류와는 상관없이 자바스크립트 코드를 출력하고자 최선을 다하지만, 내가 원하는 출력 결과가 아닐 수 있다. 따라서 출력된 자바스크립트 코드를 실행하기 전에 구문 오류를 수정하는 것이 좋다.
console.blub("Hello TypeScript!")
//Error: Property 'blub' does not exist on type 'Console'.
let fruit = "apple";
fruit = "banana"; //동일한 타입의 다른 값 할당 OK
fruit = true; //다른 타입의 값 할당 ❌
//Error: Type 'boolean' is not assignable to type 'string'.
Type...is not assignable to type...
형태의 자주 접하는 오류any
타입으로 간주 → 변수는 세상의 모든 것이 될 수 있음let rocker; //타입: any
rocker = "Joan Jett"; //타입: string
rocker.toUpperCase(); //OK
rocker = 19.99; //타입: number
rocker.toPrecision(1); //OK
rocker.toUpperCase();
//Error: Property 'toUpperCase' does not exist on type 'number'.
let rocker : string;
rocker = "Joan Jett";
타입 시스템에만 존재하는 것은 컴파일된 자바스크립트로 복사되지 않고 어떠한 영향도 주지 않는다!
let str : string = "apple"; //타입 시스템은 변경되지 ❌
let rapper = "Queen Latifah"
rapper.length //ok
rapper.push('!') // string 타입에서 자동하는지 알 수 없는 작업은 허용 ❌
//Error: Property 'push' does not exist on type 'string'.
let fruit = {
first: "apple",
second: "banana"
}
fruit.third;
//Error: Property 'third' does not exist on type '{ first: string; second: string; }'.
import
내보내는 export
구문의 표준화import { value } from "./values";
export const doubled = value * 2;
모듈 : export 또는 import가 있는 파일
스크립트: 모듈이 아닌 모든 파일
- 타입스크립트는 최신 모듈 파일을 기존 파일과 함께 실행 가능
- 모듈 파일에서 선언된 것 → export로 내보내지 않는 한 그 파일 내에서만 사용가능
- 한 모듈에서 다른 파일의 선언된 변수와 같은 이름으로 선언된 변수는 다른 파일의 변수를 가져오지 않는 한 이름 충돌이 ❌
//a.ts - 모듈
export const named = "apple"
//b.ts - 모듈
export const named = "apple"
//c.ts - **가져온 변수 named와 정의된 변수 named의 이름 충돌**
import { named } from '/a';
//Error: Import declaration conflicts with local declaration of "named"
export const named = "apple";
//Error: Individual declarations in merged declaration
//'named' must be all exported or all local
//a.ts - 일반 스크립트
const named = "apple"
//Error: Cannot redeclare block-scoped variable 'named'
//b.ts - 일반 스크립트
const named = "apple"
//Error: Cannot redeclare block-scoped variable 'named'
Cannot redeclare...
라는 오류는 export나 import문을 추가하지 않아서일 수 있다.const named = "apple"
//export {}; 추가해 강제로 모듈이 되도록 만듬
export {};
⚠️
타입스크립트는 CommonJS 같은 이전 모듈 사용법의 import, export 형태는 인식하지 못한다. 일반적으로 CommonJS 스타일의 require 함수 반환 값을 any 타입으로 인식한다.
참고자료 - 📚 러닝 타입스크립트