basic
숫자 : number
문자열 : string
논리 : boolean
배열 : array (자료형[])
optional
변수(속성)명 뒤에 ❓ 붙이면 optional parameter
const player : {
name: string,
age?: number
} = {
name: "nico"
}
// age undefined check
if (player.age && player.age < 10) {
}
Type Alias
To create a new name for a type
for 타입의 재사용
but not too much. 깔끔하고 명확해질 때까지만.
// Type Alias to every type
type Name = string // **too much. not recommend
type Age = number // **too much. not recommend
type Player = {
name: Name, // required type
age?: Age // optional type
}
const tang: Player = {
name: "tang"
}
const yoon: Player = {
name: "yoon",
age: 12
}
// argument type, function return type
function playerMaker(name: string) : Player {
return { name }
}
const playerMaker = (name: string) : Player => ({name})
const tang = playerMaker("tang")
tang.age = 13
readonly
읽기 전용. immutability(불변성)
type에 readonly 속성을 추가로 부여하면, 최초 선언 후 수정 불가
no in JS - 컴파일X
type Player = {
readonly name: string,
age?: number
}
const playerMaker = (name: string): Player => ({name})
const tang = playerMaker('tang')
tang.age = 12
🚫 tang.name = 'taeyoung'
const numbers: readonly numbers[] = [1, 2, 3, 4]
🚫 numbers.push(1)
Tuple
To specify an array with a min length and type positions
(최소 길이 + 특정 위치에 특정 타입)을 가진 배열
정해진 길이와 타입 순서를 지켜야 한다.
no in JS
const player: [string, number, boolean] = ['tang', 24, true]
🚫 player[0] = 25 // type 변경 불가
const player: readonly [string, number, boolean] = ['tang', 24, true]
🚫 player[0] = 'taeyoung' // readonly 수정 불가
undefined, null
optional type 은 undefined가 될 수 있다
type Player = {
age?: number // number | undefined
}
any (비추천)
type 지정 안 했을 때 기본값.
TS의 모든 보호장치 비활성화하고 싶을 때 사용 (탈출구)
when we use 'any', we escape the TS world
const a: any[] = [1, 2, 3, 4]
const b: any = true
🙆♀️ a + b // it will work
types exclusive to TS - type checker와 소통★
unknown
변수의 타입을 미리 알지 못 할 때 (ex.API로부터 모르는 타입의 응답)
해당 변수의 타입을 먼저 확인하도록 강제한다
let a: unknown
if (typeof a === 'number') {
let b = a + 1
}
if (typeof a === 'string') {
let b = a.toUpperCase()
}
void
아무것도 return하지 않는 함수
but, 자동으로 인식해서 굳이 지정할 필요는 없음
function hello() { // : void
console.log('x')
}
const a = hello()
🚫 a.toUpperCase()
never
When a path of code should never run
case 1. exception 발생시 return하지 않고 오류 발생
case 2. 타입이 두가지일 수도 있는 상황
// case 1
function hello(): never {
throw new Error("xxx")
}
// case 2
function hello(name: string|number) {
if (typeof name === 'string') {
name // string
} else if (typeof name === 'number'){
name // number
} else {
name // never
}
}
'Front-end > 타입스크립트로 블록체인 만들기' 카테고리의 다른 글
[TS] HW - Polymorphism, Generic Type (1) | 2023.12.21 |
---|---|
[TS] Polymorphism 다형성 (0) | 2023.12.20 |
[TS] Why not JavaScript (0) | 2023.12.18 |
[TS] Overloading (0) | 2023.12.15 |
[TS] Call Signatures (0) | 2023.12.15 |