타입스크립트(TypeScript)는 자바스크립트(JavaScript)를 기반으로 정적 타입 문법을 추가한 프로그래밍 언어이다.
✅ 자바스크립트에 설치
npm install -g typescript
✅ 새로운 React+typescript 설치
npx create-react-app my-app --template typescript
✅ React 프로젝트에 설치
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
typescript file(.ts)을 javascript file(.js)로 변환시키는 것을 컴파일 한다고 말하며 명령어는 tsc -w
이다
✔ tsconfig.json
ts 파일을 js파일로 컴파일할때 설정들을 지정할수 있는 파일
✔ 기본 타입 : Primitive type
배열과 객체 모든 변수에 타입을 지정 안해줘도 자동으로 지정이 되며 마우스 오버시 어떤 타입인지 보여준다.
두개 이상의 타입을 가진 것을 union type이라고 할 수 있다.
type result = number | string
let 이름 : result = 'kang'
이름 = 123
let 회원 : number | string[] = ['kang', 10 ] // 오류
let 회원 : (number | string)[] = ['kang', 10 ] // 정상
타입 지정을 해제하는 문법으로 오류가 발생하여도 자동적으로 오류가 안나기 때문에 타입스크립트를 쓰는 의미가 없다.
let 이름 : any = 'kang'
이름 = 123
any 와 마찬가지로 모든 자료형을 허용해주지만, 차이점으로 오류가 나면 any와 다르게 검색이 된다.
파라미터와 매개변수에 타입 지정해준다.'아무것도 없이 공허함'을 뜻하는 타입이다. 함수에 return 방지장치를 주고 싶을 때 void 타입을 활용하면 된다.
- 리턴되는 값이 없을 때 는 void를 사용한다.
- 파라미터가 옵션인 경우 사용한다.
- 파라미터 없이 실행 가능하다.
function hi (a:number) :void {
b = a
}
function hi (a? :number) :void {
b = a
}
function hi (a : (number | undefined) ) :void {
b = a
}
hi()
union type 인 경우 if 문 등을 사용하여 타입을 확정지어주어야 한다.
if 문 사용하면서 else 또는 else if 로 안끝내는 경우 에러가 발생할 수도 있기 때문에 꼭 else 또는 else if 문을 써주는 것이 좋다.
function 함수(a : (number | string) ) :number {
return a + 2
}
-> a가 number 혹은 string 이라 에러 발생한다 ~
function 함수(a : (number | string) ) :number {
if(typeof a === 'number'){
return a + 2
}
}
-> if 문으로 Narrowing 꼭 해주기!
function 함수(a : (number | string) ) :number {
return (a as number) + 2
}
if문 등의 Narrowing 문법을 안쓰고 임시로 타입을 지정준다. 하지만
편하다고 자주 쓰게 되면 안된다,
🙃그러면 언제 사용하는 것이 좋을까?
- Narrowing 할 때 사용한다.
-> 타입을 변경하는 합수는 아님- 어떤 타입이 들어올지 100% 확신할 때 사용한다. (그래서 굳이 쓸 이유x 정말 필요할때 남의코드 수정할 때만 사용) -> 디버깅용 / 비상용
타입 지정도 변수에 담아서 재활용 및 코드의 양을 줄일 수 있다.
type Animal = string | number | undefined;
let 멍멍 : Animal = 'chon'
let 멍멍 : Animal = 6
let 멍멍 : Animal
객체의 타입 지정 또한 변수를 활용하여 정리가 가능하다.
type Animal = {name : string , age : number}
let 멍멍 : Animal = {name : 'chon' , age : 6}
✔ type 결합
타입끼리 결합하여 새로운 타입도 생성 가능하다.
type Name = string;
type Age = number;
type Person = Name | Age;
type PositionX = {x : number}
type PositionY = {y : number}
type newPosition = PositionX & PositionY
// {x : number, y : number }
const 변수는 재선언 및 재할당이 불가능 하지만 자바스크립트 본연에서는 객체의 데이터는 수정이 가능하다.
const 여친 = {
name : '엠버'
}
여친.name = '유라'
// 객체의 키값 내부의 데이터는 수정가능하지만, readonly 속성을 사용하여 변경을 막을수 있다.
// 에러는 발생하나 js 파일에서 변경 및 실행은 된다. "오류만 보여주는 역할"을 한다.
type Girlfriend= {
readonly name : string
}
const 여친 :Girlfriend = {
name : '엠버'
}
여친.name = '유라' // 타입스크립트 에러 발생
인터페이스를 사용하면 함수의 인자가 좀 더 명시적으로 바뀐다. 또한 같은 타입을 사용할 경우 재사용이 가능하다는 장점이있다.
인터페이스를 사용할 때는, 함수내에 사용할 속성에 대해서만 인터페이스를 지정해줘도되며 인터페이스 내의 속성 순서를 지키지 않아도 된다.
interface Square {
color :string,
width :number,
}
let 네모 :Square = { color : 'red', width : 100 }
--------------------------------------------------------------------------
type Animal = {name : string}
type Cat = {age : number} & Animal
interface A{
name :string
}
interface A{
score:number
}
let 상품 = {brand : 'ss', serialNumber:1350, model:['TV','phone']}
interface Product{
brand:string,
serialNumber:number,
model:string[]
}
⭐ type vs interface 차이점은?
interface는 중복선언이 가능하지만 type은 중복선언 불가능하다.
interface에서 중복선언을 하면 자동 익스텐드 되기에 중복선언이 된다.
하지만 type은 엄격하기 때문에 중복선언 불가능 하다고 보면 된다.
클래스를 상속하는 클래스가 있듯이, 인터페이스 또한 extends 키워드를 사용해 인터페이스를 확장 할 수 있다.
interface Cart{
product: string,
price:number,
}
interface Add extends Cart{
card: boolean
}
let 모야: Add =
{ product : '청소기', price : 7000, card : false };
<*instance의경우>
interface Animal {
name :string
}
interface Cat extends Animal {
legs :number
}
<*type alias의 경우>
type Animal = {
name :string
}
type Cat = Animal & { legs: number }
}
interface Student {
name :string,
}
interface Teacher {
age :number
}
let 변수 :Student & Teacher = { name : 'kang', age : 100 }
type | interface | |
---|---|---|
지정가능형식 | 타입, 원시값, 유니온 등 여러가지 지정가능 | 타입만 지정 가능 |
확장 특성 | 페쇄적이고, 제한 사항 많아 확장 어려움 | declaration merging으로 확장 가능하기에 자유로움 |
파일 번들링 | 새로운 타입 생성시 번들링 | 컴파일 시점에 번들링 |
typescript 공식 사이트 : https://www.typescriptlang.org/