[TypeScript] 강의 정리

DD·2021년 5월 20일
0

명령어

$ yarn init -y //
$ yarn add typescript ts-node
// ts-node는 ts파일을 js로 컴파일하지 않고도 실행할 수 있게 해주는 모듈이다
$ yarn run ts-node {.ts}
$ yarn run tsc --init // 프로젝트에 타입스크립트 설정이 만들어짐 (tsconfig.json)
$

tsconfig.con

  • target : 컴파일한 코드가 어떤 JS 환경에서 실행될지. (기본 ES5)

  • outDir : 컴파일한 코드를 어디에 저장할지. (기본 ./)

기본 내용

모든 내용에 :type을 적을 필요는 없다.

	let count = 0
    	count +=1
	// 이 경우 :number를 붙여주지 않아도 자동으로 number로 인식한다 (0을 할당했기에) 

타입 뿐 아니라 할당 값 종류도 지정할 수 있다

let color : 'red' | 'orange' | 'yellow' = 'red'

interface, type로 class, object의 타입을 지정할 수 있다.

interface Shape {
    getArea()
}

type ShapeType = {
    getArea()
}

class Circle implements Shape {
    ...
    getArea(){
        return this.width * this.height
    }
} 
  • 이 class는 반드시 getArea 메소드를 작성해야한다.
  • 상속의 override와는 다르다!
interface Person {
    name: string,
    age?: number
}
  
type Person = {
    name: string,
    age?: number
}
  
const person: Person {
    name : 'DD',
    age : 99 // 생략가능
}    
  • ?:로 지정한 경우에는 해당 속성이 있어도, 없어도 컴파일 에러가 발생하지 않는다.

interface, type에도 상속이 가능하다

interface Person {
    name: string,
    age?: number,
}

interface Developer extends Person {
    skills: string[]
}
  
type Person = {
    name: string,
    age?: number,
}

type Developer = Person & {
    skills: string[]
}

class의 constructor에 private, public 적용

흔히 constructor에서 전달받은 파라미터를 this.a = a, this.b = b등으로 인스턴스의 속성에 할당하는 경우가 있다.

타입스크립트에서는 이 경우 constructor에 private, public을 지정해 그 과정을 단축할 수 있다.

class Sample {
	constructor(private a, public b)
  ...
}
  
const sample = new Sample('private', 'public')

sample.a // private이기 때문에 접근이 불가능하다.
sample.b // public이기 때문에 접근이 가능하다.

Generics <T>

profile
기억보단 기록을 / TIL 전용 => https://velog.io/@jjuny546

0개의 댓글