JS & TS/TypeScript

[TypeScript] Union, Literal

Bay Im 2024. 2. 13. 16:42
  • literal 타입
    • 원시 타입보다 더 구체적인 원시 타입
    • 원시 값 자체가 타입이 된다.
  • union 타입
    • union(|)은 값에 허용되는 타입을 두 개 이상으로 가능한 타입으로 확장하는 것
      • ex)
        • phone: number | string;
        • addr?: string;
    • 확장된 타입에서 어느 하나의 타입에 할당 가능
    type Member = {
       name: string,
       addr: string,
       discountRate: number;
    };
    type Guest = {
       name: string,
       age: number,
    };
    type Customer= Member | Guest;
    
  • union type - narrowing과 type guard
    • union type에서 특정 타입에만 존재하는 속성에 접근하고 싶을 때 type guard를 통해 type narrowing
    • narrowing
      • 값이 더 구체적인 타입임을 코드에서 유추하는 것
    • type guard
      • narrowing을 하기 위한 논리적인 검사
    • 값 할당을 통한 narrowing
      • 변수에 값을 직접 할당하면 할당된 값의 타입으로 좁혀진다.
    • typeof 검사를 통한 narrowing
      • 조건문에서 type을 확인하여 타입을 좁힌다.
    • 조건 검사를 통한 narrowing
      • if 문
  • strictNullChecks
    • 엄격한 null 검사 활성화/비활성화
      • null 혹은 undefined 값을 참조/할당 했을 때 타입 에러 발생 여부
    • strictNullChecks 활성화
      • 다른 타입이 필요한 위치에서 null 혹은 undefined 값을 참조/할당 하는 것을 방지
      • 활성화해야만 null 및 undefined에 대한 오류로부터 안전해진다.
    • strictNullChecks 비활성화
      • 다른 타입이 필요한 위치에서 null 혹은 undefined 값을 참조/할당 하는 것을 방지하지 않는다.
  • 타입 별칭(Alias)
    • 자주 사용될 타입에 이름 붙이기
    • ex)
      • type PersonInfo ={
        	id: number,
        	name: string,
        	age: number,
        	address: string;
        }
        // 아래처럼 타입 만들기 
        const something = ({id, name, age, addess}: PersonInfo)
        => {
        	...
        }
728x90

'JS & TS > TypeScript' 카테고리의 다른 글

[TypeScript] Array, Tuple  (0) 2024.02.13
[TypeScript] Function  (0) 2024.02.13
[TypeScript] Object  (0) 2024.02.13
[TypeScript] Type System  (0) 2024.02.13
[TypeScript] TypeScript란?  (0) 2024.02.13