[TypeScript] 타입과 문자열

어느 개발자·2021년 3월 29일
0

TypeScript

목록 보기
2/5
post-thumbnail

1. 문자열

문자열은 기본적으로 아래와 같이 선언하며, + 연산자를 통해 문자열을 연결할 수 있으며 백틱도 사용 가능하다.

let emotion: string = "happy"
let intro: string = "one =" + String(1) + "\ntwo = " + String(2)

let multi_line: string = `
  one = 1
  two = 2
`

2. 배열

let fruits: string[] = ["banana", "apple", "mango"]
let fruits2: string[] = []

fruits2.push("banana")
fruits2.push("apple")
fruits2.push("mango")

(1) 제네릭

배열을 선언할 때 제네릭 타입으로 선언할 수 있다.

let num: Array<number> = [1,2,3]
let num2: Array<number> = new Array<number>()

num2.push(1)
num2.push(2)
num2.push(3)

(2) 다차원 배열

let matrix: number[][] = [
	[1,0,0],[0,1,0],[0,0,1]
]

3. 유니언 타입 (union types)

2개 이상으로 입력된 타입에 대해 하나의 타입으로 정의한다. 유니언 타입은 타입을 나열하는 형태로 선언한다.

let unionX: string | number = 1
let unionY: boolean | string = true

console.log(typeof unionX, unionX)
console.log(typeof unionY, unionY)

// 실행결과
number 1
boolean true

유니언 타입을 함수의 매개변수 타입과 반환 타입으로 사용할 수 있다.

function typeCheck(p: string | number): string | number {
	return p
}

let type = typeCheck(1)
let type2 = typeCheck("1")

console.log(typeof type, type)
console.log(typeof type2, type2)

// 실행결과
number 1
string 1

4. 디스트럭처링 (Destructuring)

디스트럭처링은 배열이나 객체에서 데이터를 선택적으로 추출할 수 있는 자바스크립트 표현식이다.

// ES6
let params = ['happy', 100]
let [emotion, num] = params

0개의 댓글