타입스크립트 D10 - 완강

nearworld·2022년 7월 26일
0

typescript

목록 보기
10/28

Literal types

const metrics = 'cm' | 'inch';
const quantity = 50 | 100;

타입의 값을 명시적으로 지정하여 특정 값만 할당할 수 있도록 제한을 둘 수 있는 타입 방식이다.

type alias 사용

type Quantity = 50 | 100;
let quantity: Quantity = 51 // error
let quantity2: Quantity = 50
let quantity3: Quantity = 100
type Metrics = 'cm' | 'inch';
const metrics: Metrics = 'cm';

type alias를 이용하여 여러 다른 변수에 똑같은 타입 지정을 하면 생산성이 증대된다.

Nullable types

function greet(name: string) {
  console.log(name);
}

greet(null) // error

greet함수의 인자에 타입 string이 지정되어 있으므로 null값을 패스하는건 `Argument of type null is not assignable to parameter of type string 에러를 발생시킨다.

//tsconfig.json

"strict": true,
// "strictNullChecks": true

tsconfig.json 파일을 보면 strictNullChecks 옵션이 비활성화되어 있고 strict 옵션이 true가 되어있는 것을 볼 수 있는데 strict 옵션이 활성화되어있다면 strictNullChecks 기능도 포함하여 활성화된 상태다. "strictNullChecks": false로 지정해주면 strict: true여도 null타입에 대한 엄격한 타입 체크가 해제되고 다음과 같은 상황이 발생하는게 가능해진다.

function greet(name: string) {
 console.log(name); 
}
greet(null); // 정상 작동

위와 같은 상황을 예방하기 위하여 structNullChecks: false 옵션은 조심하는 것이 좋다. 그렇다면, 프로그램 내에서 특정 코드만 예외적으로 null값을 패스해도 되는 상황이 필요할 땐 유니온 타입 지정으로 해결할 수 있다.

function greet(name: string | null) {
  console.log(name);
}
greet(null); // 정상 작동

Optional Chaining

type Customer = {
  birthday: Date
}

function getCustomer(id: number): Customer | null | undefined {
  return id === 0: null ? { birthday: new Date() }
}
  
let customer = getCustomer(0);
console.log(customer.birthday); // 에러

위 코드의 문제는 id값이 0이 되었기 때문에 getCustomer()함수는 null을 리턴하였고 customer에는 null이 할당된 상황이다.
그러므로 .birthday 프로퍼티를 사용할 수 없다.
Object is possibly null에러가 터지고 프로그램이 충돌할 것이다.

이를 방지하기 위한 방법으로

let customer = getCustomer(0);
if (customer !== null && customer !== undefined )
  console.log(customer.birthday);

if문을 두는 type narrowing으로 에러를 방지할 수 있다.

하지만 더 간단하게 하는 방법이 있다.

customer?.birthday;

? optional chaining을 사용한다면 customernull값일때 .birthday를 읽지않고 넘어가 에러를 방지할 수 있다.

profile
깃허브: https://github.com/nearworld

0개의 댓글