ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 5. Union Type
    Typescript 2022. 10. 17. 17:42

     

    Union Types
    • 단일 타입이 아닌 다중 타입을 가질 수 있음
    • | 사용하여 여러 타입 명시
    let ages: number | string
    
    ages = 15 // OK
    ages = '15' // OK

     

     

    • Custom Type Union
    type Point = { x: number, y: number }
    type Loc = { lat: number, long: number }
    
    let coordinates: Point | Loc
    coordinates = { x: 4, y: 8 } // OK
    coordinates = { lat: 55.2342, long: 234942.2 } // OK

     

     

     

    Narrowing the Type (타입 좁히기)
    • Union Type의 값을 특정 타입으로 확인하는 단계 추가
    • typeof 구문 사용
    const getPrice = (price: number | string): number => {
    	return price.replace('$', '') // ERROR - Property 'replace' does not exist on type 'number'
        
        if (typeof price === 'string') {
        	return parseFloat(price)
        } else {
        	return price
        }
    }

     

     

     

    Array Union Type
    • 배열 안에 허용되는 타입들을 괄호로 묶은 후 뒤에 대괄호 표시
    // string과 number를 함께 가지는 배열
    let unionArray: (string | number)[]
    
    // string만 가지는 배열과 number만 가지는 배열
    let newUnionArray: string[] | number[]
    type Point = { x: number, y: number }
    type Loc = { lat: number, long: number }
    
    let position: (Point | Loc)[]
    position.push({ x: 45, y: 7 }) // OK
    position.push({ lat: 42342.11, long: 66.25 }) // OK

     

     

     

    Literal Type
    • 명확한 값(타입)을 갖는 변수 선언
    • 해당 변수에 재할당 불가
    let tempNum: 0
    tempNum = 5 // ERROR - tempNum is 0 type. not 5
    
    let tempString: 'hi'
    tempString = 'hello' // ERROR - tempString is 'hi' type. not 'hello'

     

     

    • Union Type을 사용하여 해당 하는 값만 받아옴
    const giveAnswer = (answer: 'yes' | 'no' | 'maybe'): string => {
    	return `The answer is ${answer}!`
    }
    
    giveAnswer('no') // OK
    giveAnswer('Love') // ERROR - answer is 'yes' or 'no' or 'maybe' type
    let mood: 'HAPPY' | 'SAD' = 'HAPPY'
    mood = 'SAD' // OK
    mood = 'ANGRY' // ERROR
    
    type Week = 'Monday' | 'Tuesday' | 'Wednesday'
    let today: Week = 'Saturday' // ERROR

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    'Typescript' 카테고리의 다른 글

    7. Interface  (0) 2022.10.19
    6. Tuple & Enum  (0) 2022.10.18
    4. Array Type  (0) 2022.10.17
    3. Object Type  (0) 2022.10.13
    2. Function Parameter Annotation  (0) 2022.10.13
Designed by Tistory.