Learning TypeScript 3장

hyena_lee·2023년 3월 5일
0

TypeScript

목록 보기
3/7
post-thumbnail

유니언(Union)

  • 값에 허용된 타입을 두 개 이상의 가능한 타입으로 확장하는 것
  • "이거 혹은 저거" 같은 타입을 Union 이라고 함
  • 유니언을 선언한 모든 가능한 타입에 존재하는 멤버 속성에만 접근 할 수 있다.
// sring | number
let bts1: string | number;
let bts2 = Math.random() > 0.5 ? taetae : 29;
bts2.toString();   // ok
bts2.toFixed();  // Error: property "toFixed" does not exist on type 'string |number'.

내로잉(Narrowing)

  • 값에 허용된 타입이 하나 이상의 가능한 타입이 되지 않도록 좁히는 것!!
  • 타입을 좁히는데 사용할 수 있는 논리적 검사를 타입 가드 라고 한다.

1. 값 할당을 통한 내로잉

let animal = number | string;
animal = "rabbit";
animal.toUpperCase();   // ok: stirng
animal.toFixed();
// Error: property 'toFixed' does not exist on type 'string'

변수에 유니언 타입 애너테이션이 명시되고 초깃값이 주어질 때 값 할당 내로딩이 작동된다. 타입스크립트는 변수가 나중에 유니언 타입으로 선언된 타입 중 하나의 값을 받을 수 있지만, 처음에는 할당된 값의 타입으로 시작한다는 것을 이해헤야한다.

2. 조건 검사를 통한 내로잉

  • if 문을 통해 변수의 값을 좁히는 방법을 사용한다.
let bts = Math.randon() > 0.5 ? "taetae" : 29;

if(bts === "taetae") {
  // bts. string 타입
  bts.toUpperCase();   // ok
}


// bts : number | string 타입
bts.toUpperCase();

// Error : Property 'toUpperCase" does not exist on type 'string| number'
// Property 'toUpperCase' does not exist on type 'number'

3. typeof 검사를 통한 내로잉

  • 직접 값을 확인해 타입을 좁히기도 하지만, typeof 연사자를 사용할 수 있다.
let bts = Math.randon() > 0.5 ? "taetae" : 29;

bts.toString();

if(typeof bts === "string") {
  // string
  bts.toUpperCase();
if(typeof bts === "number") {
  // number
  bts.toFixed();

리터럴 타입 (Literal type)

  • 원시 타입 값 중 어떤 것이 아닌 특정 원시값으로 알려진 타입이 리터럴 타입이라고 한다.
  • 원시 타입 string 은 존재 할 수 있는 모든 가능한 문자열의 집합을 나타낸다.
  • 즉, 리터럴 타입인 "coughing" 는 하나의 문자열만 나타낸다.
const myState = "coughing" 

1.리터럴 할당 가능성
: number와 string 과 같은 서로 다른 원시 타입이 서로 할당되지 못한다.
: 즉 0과 1 처럼 동일한 원시타입일지라도 서로 다른 리터럴 타입은 서로 할당 할 수 없다.

let bts:"Taetae" = "Taetae;
bts = "Blackpink"; 		// Error : Type "Blackpink" is not assignable to type "Taetae".


let someSong: "";
bts = someSong;
// Error : type 'string' is not assignable to type 'Taetae'.

엄격한 null 검사

: null과 undefined를 활성화 할 지 여부 결정하는 것.

  • strictNullCecks는 엄격한 null 검사를 활성화 할지 여부 결정하고 strictNullChecks를 비활성하면 코드의 모든 타입에 | null | undefined를 추가해야 모든 변수가 null | undefined를 할당한다.
let myName: string;

// strictNullChecks : false
myName = null;  // ok

// strictNullChecks : true
myNamn = null;  // Error : Type. 'null' is not assignable to type 'string'.
  1. 참 검사를 통한 내로잉
  • 참 | truthy 는 && 연사자 | if 문처럼 boolean 문맥에서 true 간주.
  • false, 0, -0, on, "", null, undefined, NaN 처럼 falsy 로 정의된 값을 제외한 모든 값은 모두 참이다.
let breakfast = Math.random() > 0.5 ? "McDonald" : undefined;
	if(breakfast) {
  		breakfast.toUpperCase();   // ok
    breakfast.toUpperCase();
  // Error : Object is possibly 'undefined'
      
 
      

breakfast && breakfast.toUpperCase();    // ok: string | undefined
breakfast?.toUpperCase();
let weekend = Math.random() > 0.5 && "Play Catch Ball";
if(weekend) {
  weekend;   // type: string
} else {
 	weekend;  // type: false | string
}
  1. 초깃값이 없는 변수
  • 초깃값이 없는 변수는 기본적으로 undefined
  • 값이 할당될 때까지 변수가 undefined 임을 이해하함.
let weekend: string;
weekend?.length;
// Error :  Variable 'weekend' is used before being assingend.

weekend = "Play Catch Ball";
weekend.length;  // ok

타입 별칭
: type 키워드를 이용해서 타입에 대한 변수를 생성한다.

  • 재사용하는 타입에 더 쉬운 이름을 할당하는 타입별칭 dla
  • type 새로운 이른 = 타입 형태를 갖는다. (편의상 파스칼 케이스 이름으로 지정)
  • 타입 별칭은 "복사해서 붙여넣기" 작동
  • 타입 별칭은 자바스크립트에 존재 하지 않는다
type HyungGu = ..; 
type HyungGu = boolean | number | string | null | undefinedl
let HyunGuFirst: HyunGu;
let HyunGuSecond: HyunGu;
let HyunGuThird: HyunGu;

[Reference]
1. Learning typeScript(조시 골드버그/고승원/한빛미디어_2023)

profile
실수를 두려워 말고 계속 도전 하는 개발자의 여정!

0개의 댓글