Frontend/Typescript

typescript 설치부터 사용법 정리

Developer Mobssie 2021. 5. 24. 23:46

타입스크립트는 변수랑 함수의매개변수랑 리턴값에 타입이 붙은 것이다.

설치

npm init

npm i typescript

npm i -g typescript (명령어로 설치/+ 전역설치)] 

= npx tsc lecture.ts -w

프로젝트에 설치한 버젼이랑 같이 설치가되서 npx로 해야한다.

 

tsc 엔터 (타입스크립트 컴파일 하는명령어)

tsc lecture (해당하는 폴더에)

tsc를 통해서 ts를 컴파일해서 js로 변경해서 html에는 항상 js를 연결.

 [자동으로 컴파일]

tsc lecture.ts -w

 

HTMLDivElement : 타입스크립트에서 만들어  놓음

Package-lock : lock파일은 github에 같이 올려야함.

정확한 버젼이기때문에 똑같은 버젼이 깔림.

Package.js : 범위

 

[tsconfig.ts]

Target:  es6로 하고 바벨,

module

undefined와 null을 구분하는 module

"strictNullChecks": true,

 

[error 해결]

에러코드 나오면 코드를 구글에 검색

예// TS2304 

 

tsconfig.ts에서 “lib”: [“ES5” .. ..]

도저히 해결 할 수없는 에러일때에는 뒤에 느낌표를 붙여준다.

 

 

 

[this와 타입 범위 이해]

this를 썻다. 그런데 arrow function이 아닌 그냥 function이면 this의 타입을 첫번째 매개변수로 넣어 줘야 한다. this 타입추론이 정확해진다.

 

btn.addEventListener('click', function(this: HTMLButtonElement, e: Event){
const myChoice = this.textContext as keyof RSP;

as 를 써서 타입을 정확하게 맞춰주는것.

타입스크립트가 스스로 추론하지 못하는것들을 범위를 쫍혀줘야 한다.(타이트하게)

let imgCoords: RSP[keyof RSP] = '0';

범위를 잘 이해해야함.

 

[interface]

interface는 확장할수있다. 객체에서 사용.

따로따로 적어주면 합쳐진다.

어떤값이 들어올지 모르면 엄격하게 하지 않을때

Interface RSP {

  [c: string] : string

}

Interface RSP {
  [c: string] : string
}

이런 식으로 클래스 표현이 가능하다.

 

interface Example {
  new (a: number, b: number): number
}

new를 붙이면 class를 interface로 표현 가능하다.

 

interface Example {
    add: (a: number, b: number) => number
  } // 객체의 속성. 함수타입
  const ex: Example = {
    add: (a, b) => {
    return a + b;
  }
}

 

 

[제네릭]

짝마추기

document.addEventListener<'submit'>('submit', () => {

})

’submit’이 가능한 이유는 타입스크립트에 선언되어있기때문,

submita 이렇게 다른 문자열이 오면 에러가 난다.

 

function add(a: string, b: string): string{
  return a + b;
}
function add(a: number, b: number): number{
  return a + b;
}

이렇게 표현하고 싶을때 사용한다

 

interface obj<T> {
  add: (a: T, b: T) => T;
}
const a: obj<number> = {
  add: (a, b) => a + b,
}
const b: obj<string> = {
  add: (a, b) => a + b,
}
a.add(1, 2);
a.add('1', '2'); // error
b.add(1, 2); // error
b.add('1', '2');

 

제네릭 타입제한 

ex <T extends string>

interface obj<T extends string> {
  add: (a: T, b: T) => T;
}
const a: obj<number> = {
  add: (a, b) => a + b,
} // error
const b: obj<string> = {
  add: (a, b) => a + b,
}
a.add(1, 2);
b.add('1', '2');

 

[type]

유니언이 필요한경우 | type을 사용

 

[keyof]

let imgCoords: RSP[keyof RSP] = ‘0’

>> 중복을 줄일수잇어서 좋다

 

[as]

강제로 변환해주는 것(범위를 좁혀주는 작업)

작은 집합은 큰 집합에 들어갈수있는데 큰 집합은 작은 집합으로 들어가지 못하기때문에 똑같이 마춰주는게 베스트!

 

[private, public, protected]

public < protected < private

public: 인스턴스에서도 접근가능.

protected: 자식들도 접근가능. extends 로 접근가는데. (부모는 안됨)

private: 나한테에서만 접근할수있는것.

 

[implements]

new를 쓴다면 class를 사용하고, extends를 실제로 사용하면 class

interface를 implements로 구현만 하면.. implements