본문 바로가기
FRONTEND/Javascript

220801 Typescript Handbook

by 또야또야 2022. 8. 1.
반응형

Typescript 핸드북

원시타입 (Primitives) : string, number, boolean

Array

[1, 2, 3] 과 같은 Array 는 number[]Array<number>(generics 타입) 를 이용하여 작성될 수 있습니다.

let list_1: number[] = [1, 2, 3]
let list_2: Array<number> = [1, 2, 3]

any

any 는 자유로운 값을 받을때 사용합니다.

변수의 Type 정의(Annotation)

let myName: string = 'Alice'
let myName = 'Alice'          // Typescript 가 내부에서 정의하기 때문에 특별히 type 정의를 하지 않아도 됩니다.

함수 (Function)

Parameter Type 정의

function greet(name: string) {
  console.log('Hello, ' + name.toUpperCase() + '!!')
}

greet('MIKE')  // OK
greet(42)      // Error!

Return 타입 정의

function getFavoriteNumber(): number {
  return 26
}

익명 함수 (Anonymous Function)

const names = ['Alice', 'Bob', 'Eve']

names.forEach(s => {
  // Error Property 'toUppercase' does not exist on type 'string' ... ?
  // console.log(s.toUppercase())
  console.log(s.toUpperCase())
})

오브젝트 타입 (Object)

Parameter Type 정의

// Object 형태의 parameter 의 타입정의
function printCoord (pt: { x: number, y: number }) {
  console.log('@@ parameter X, Y : ', pt.x, pt.y)
}

printCoord({ x: 3, y: 7 })
// Object Destructing :: ECMAScript 2015
function printCoord ({ x, y }: { x: number, y: number }) {
  console.log('@@ parameter X, Y : ', x, y)
}

printCoord({ x: 3, y: 7 })

Optional Properties

Object type 은 ? 를 이용해 선택적 (optional) 프로퍼티를 가질 수 있습니다.

// "?" Option 프로퍼티 :: 있을수도, 없을 수도 있음
function printName (obj: { first: string, last?: string }) {
  // ...
}

printName({ first: 'Bob' })
printName({ first: 'Alice', last: 'Alisson' })

Union Types

Union Type 정의

function printId (id: number | string) {
  console.log('Your Id is : ' + id)
}

printId(101)   // OK
printId('202') // OK
printId({ myID: 22342 }) // Error
// Argument of type '{ myID: number; }' is not assignable to parameter of type 'string | number'.

Union Types 사용하기

// 올바른 사용법
function printId (id: number | string) {
  if (typeof id === 'string') console.log(id.toUpperCase())
  else console.log(id)
}

printId(101)   // OK
printId('202') // OK
printId({ myID: 22342 }) // Error

// ----

function welcomePeople (x: string[] | string) {
  if (Array.isArray(x)) console.log('Hello, ', x.join(' and '))
  else console.log('Welcome lone traveler', x)
}

welcomePeople(['Bob', 'Jacob', 'Alice'])
welcomePeople('Bob')

Type Aliases

type 정의 는 타입을 정의하는 방법입니다.

type Point = {
  x: number
  y: number
}

function printCoord (pt: Point) {
  console.log('@@ parameter X, Y : ', pt.x, pt.y)
}

printCoord({ x: 100, y: 100 })

Interfaces

Interface 정의 은 object type 을 정의하는 또 다른 방법 입니다.

interface Point {
  x: number
  y: number
}

function printCoord (pt: Point) {
  console.log('@@ parameter X, Y : ', pt.x, pt.y)
}

printCoord({ x: 100, y: 100 })

Type Aliases 와 Interface 의 차이?

Type 정의와 Interface 는 비슷해서 자유롭게 사용하면 됩니다.
대부분 interface 의 특징은 type 에서 사용 가능하지만 가장 다른 특징은 type 은 새로 프로퍼티를 추가할 수 없고, interface 는 항상 확장가능합니다.

타입 단언 (Type Assertion)

document.getElementById
Typescript 는 HTMLElement 중 특정한 요소만 반환한다는 것을 알 것입니다. 하지만 우리가 원하는 결과값은 주어진 ID 를 가진 HTMLCanvasElement 입니다.

// 동일함
const myCanvas = document.getElementById('main_canvas') as HTMLCanvasElement
const myCanvas = <HTMLCanvasElement>document.getElementById('main_canvas')

Literal Types

string 이나 number 에, 특정한 string/number 타입을 설정할 수 있습니다.

// 변수 타입 literal 설정
let x: 'hello' = 'hello'

x = 'hello' // OK
x = 'howdy' // Error
// parameter 타입 literal 설정
function print (s: string, alignment: 'left' | 'right' | 'center') {
  // ...
}

print('Hello World', 'left') // OK
print('G\'day', 'centre')    // Error
// return 타입 literal 설정
function compare (a: string, b: string): -1 | 0 | 1 {
  return a === b ? 0 : (a > b ? 1 : -1)
}
// Interface 와 literal 둘다 확인
interface Options {
  width: number
}

function configure (x: Options | 'auto') {
  // ...
}

configure({ width: 100 }) // OK
configure('auto')         // OK
configure('automatic')    // Error

nullundefined

  • strictNullChecks off 상태 : null 이나 undefined 값에 접근할 수 있습니다.
  • strictNullChecks on 상태 : null 값을 undefined 를 확인합니다.
function doSomething (x: string | null) {
  if (x === null) { /* ... */ }
  else console.log('Hello, ', x.toUpperCase())
}

Non-null 단언 연산자 (!)

Typescript 는 특정한 체크 없이, 특별한 nullundefined 를 제거하기위한 문법이 있습니다.
표현식을 쓰고 후에 ! 를 씁니다. 이 문법은 null 이나 undefined 가 아닌 값의 타입 단언을 효과적으로 만들어줍니다.

function liveDangerously (x?: number | null) {
  console.log(x!.toFixed())
}

반응형

댓글