Lai_Khan
개발 & 공부 일지
Lai_Khan
전체 방문자
오늘
어제
  • 전체보기 (69)
    • 공부 (60)
      • 자료구조 & 알고리즘 (4)
      • 웹 (1)
      • JAVA (3)
      • Spring (8)
      • JPA (0)
      • 네트워크 (4)
      • Kubernetes (4)
      • Typescript (5)
      • React (1)
      • 기타 (3)
      • [부스트코스] 웹 프로그래밍 (13)
      • 정보처리기사 (1)
      • 백준 2020년 1~2월 알고리즘 (12)
    • 프로젝트 (0)
    • 취준 (1)
    • 책 (3)
    • 잡담 (5)

블로그 메뉴

  • 홈
  • 방명록

공지사항

인기 글

태그

  • 자바
  • kubernetes
  • 클래스
  • java
  • 웹
  • typescript
  • 스프링
  • 네트워크
  • API
  • 브라우저
  • 벡엔드
  • http
  • OutOfPath
  • 백엔드
  • JPA
  • 객체
  • Spring
  • 코드리뷰
  • 부스트코스
  • proxy

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Lai_Khan

개발 & 공부 일지

[Typescript] Type assertion, Type alias
공부/Typescript

[Typescript] Type assertion, Type alias

2020. 4. 24. 00:45

Type assertion

형변환과는 다르다.

'타입이 이것이다' 라고 컴파일러에게 알려주는 것을 의미한다.

문법적으로 두가지 방법이 있다.

  • 변수 as 강제할 타입 (권장)
  • <강제할 타입> 변수
let value: any = "this is a string";

let strLength: number = (<string>value).length;
let strLength: number = (value as string).length;

/*
1. 주로 넓은 타입에서 좁은 타입으로 강제하는 경우가 많다.
2. jsx에서는 as를 쓴다.
*/

 

Type alias

별명.

인터페이스와 비슷하다.

주로 쓰는 경우 : Primitive, Union Type, Tuple. 여러번 쓸 때.

직접 작성해야 하는 타입을 다른 이름으로 지정할 수 있다.

만들어진 타입의 refer로 사용하는 것이지 타입을 만드는 것이 아니다.

 

코드예시

Aliasing Primitive

type MyStringType = string;

const str = 'world';

let myStr: MyStringType = 'hello';
myStr = str;
// 별 의미 없다.. 안씀.

Aliasing Union Type

let person: string | number = 0;
person = 'Mark';

type StringIrNumber = string | number;

let another: StringOrNumber = 0;
another = 'Anna';

/*
1. 유니온 타입은 A도 가능하고 B도 가능한  타입
2. 길게 쓰는 걸 짧게
*/

유니온은 A도 되고 B도 되는 타입인데 이게 매번 쓰기 너무 기니까 짧게 줄여쓰는 용도

Aliasing Tuple

let person: [string, number] = ['Mark', 35];

type PersonTuple = [string, number];

let another: PersonTuple = ['Anna', 24];

// 1. 튜플 타입에 별칭을 줘서 여러 군데서 사용할 수 있게 한다.

마찬가지로 튜플 타입에 별명을 붙여서 간편하게 쓰는 용도다.

 

인터페이스와의 차이점

type Alias = { num: number };

interface Interface {
    num: number;
}

declare function aliased(arg: Alias): Alias;
declare function interfaced(arg: Interface): Interface;

/*
1. type alias는 object literal type으로
2. interface는 interface로
*/

1. 컴파일러가 에러가 나서 잘못된 부분을 알려줄때 인터페이스는 인터페이스로 알려주는데 Alias는 object type 이름으로 알려준다.

type PersonAlias = {
    name: string;
    age: number;
}

interface IPerson extends PersonAlias {

}

let ip: IPerson = {
    name: 'Mark',
    age: 35
};

class PersonImpl implements PersonAlias {
    name: string;
    age: number;
    
    hello() {
        console.log('안녕하세요');
    }
}

let pi: PersonImpl = new PersonImpl();
pi.hello();

class PersonChild extends PersonAlias = {

}

/*
1. 당연한건 type alias끼리는 extends, implements 불가
2. interface extends type alias 가능
3. class implements type alias 가능
4. class extends type alias 불가 (interface도 마찬가지)
5. 마치 interface처럼 동작한다.
*/

2. 상속, implement 다 안됨. type alias끼리는. 다만 인터페이스처럼 쓰면 인터페이스처럼 써진다. 상속하고 implement하고 되는데 권장하는 타입은 아니다. 그냥 인터페이스 쓰는게 명시적으로 훨씬 낫다.

저작자표시 비영리 변경금지 (새창열림)

'공부 > Typescript' 카테고리의 다른 글

[Typescript] Interface (인터페이스)  (0) 2020.04.24
[Typescript] var, let, const  (0) 2020.04.22
[Typescript] 자료형  (0) 2020.04.20
[Typescript] 개발환경 구축 및 컴파일러 사용  (0) 2020.04.19
    '공부/Typescript' 카테고리의 다른 글
    • [Typescript] Interface (인터페이스)
    • [Typescript] var, let, const
    • [Typescript] 자료형
    • [Typescript] 개발환경 구축 및 컴파일러 사용
    Lai_Khan
    Lai_Khan

    티스토리툴바