[TIL] [Typescript] 기본 개념

이나현·2021년 9월 6일
0

Typescript

목록 보기
1/3
post-thumbnail

1)Type Narrowing

  • if문 등으로 타입을 하나로 정해주는 것
function 함수(x : number | string) {
return x + 1 ; //error
(이유: union type에는 조작을 못하게 막아놓음) 
//solution
function 함수 (x: number | string) {
  if( typeof x === 'number) {
    return x + 1
  } else if( typeof x=== 'string') {
    return x + 1
  } else {
    return 0
  }
}

이렇게 타입을 파라미터로 검사해서 코드를 짜야 정상적으로 작동

단, 함수 안에서 if문을 쓸 때에는 마지막 else {}가 없으면 에러가 남

2) Type Assertion

  • 타입을 간편하게 assert할 수도 있음
  • "이 변수의 타입을 number로 생각해주세요"
    ex) 변수명 as string
function 함수 ( x: number | string) {
  return (x as number) + 1
}

console.log(함수(123)) // 124

as 키워드의 특징
1. as 키워드는 union type 같은 복잡한 타입을 하나의 정확한 타입으로 줄이는 역할을 수행
2. 실제 코드 실행결과는 as 있을 때나 없을 때나 동일

실제로 정확한 코드를 작성하려면? Type Narrowing을 쓰자!

as 문법 사용?
1. 임시로 에러해결
2. 컴파일러 에러가 날 때

3) 타입 정의가 너무 길면 Type Aliases

  • 타입이 길게 나열되어 있으면 보기가 싫음 > 변수에 담아 사용
type Animal = string | number | undefined;
let 동물 : Animal

type 타입변수명 = 타입종류

//object 타입
type 사람 = {
  name: string, 
  age: number,
}
let teacher: 사람 = {name: '나현', age: 28}

4) readonly로 잠그기

const 출생지역 = 'seoul';
출생지역 = 'busan' // error

object 자료를 const에 집어넣어도 object 내부는 마음대로 변경가능

const 여친 = {
  name: '나현'
  }
여친.name = '이나현'; //error 안남
type GirlFriend = {
  readonly name : string,
}

let 여친: GirlFriend = {
  name: '나현'
}

여친.name = '이나현' //error

한번 부여된 후엔 앞으로 바뀌면 안될 속성들을 readonly로 잠궈버림

5) 속성 몇 개가 선택사항이라면?

  • 어떤 속성이 선택사항이라면 물음표 연산자만 추가하면 된다!
type Square = {
  color? string, 
  width: number,
}

let 네모2 : Square = {
  width: 100
}

물음표 연산자는 'undefined라는 타입도 가질 수 있다~'라는 뜻

6) type 키워드를 여러개 합칠 수 있음

type Name = string;
type Age = number;
type NewOne = Name | Age;// Union type

7) type 키워드는 재정의 불가!

profile
technology blog

0개의 댓글