✊ 필오의 개발일지
Back to Posts
2017년 11월 18일

4/ 타입추론, Type assertions, Type alias

4/ 타입추론, Type assertions, Type alias

타입스크립트 정리 글은 이웅재님의 강의 강의록 을 참고하여 작성하였습니다. (짱짱) 오류가 있다면 언제든지 댓글 부탁드립니다.

목표 이 포스팅과 interface 포스팅에서는 타입을 명시하는 방법을 배웁니다. 타입을 명시하지 않아도 추론이 가능하며, 강제 타입선언, 별명을 붙여가며 타입을 선언하는 방식 등을 배웁니다.


1. let과 const의 타입 추론

let a: string = '진호'; let b = '승민'; const c: string = '나영'; const d = '슬기'; // 리터럴 타입

재할당 redeclare

보통은 const를 사용하며, let을 쓰면서 명시적으로도 값이 바껴지는 변수라고도 표시한다.


2. Type assertions (assertions:‘단언’)

let someValue: any = 'this is a string'; let strLength: number = (<string>someValue).length; let strLength: number = (someValue as string).length; /* 1. 주로 넓은 타입에서 좁은 타입으로 강제하는 경우가 많다. 2. jsx 에서는 as 를 쓴다. */

3. Type alias (alias:‘별명’)

타입에 별명을 붙인다고 생각하면 된다.

// Aliaing Primitive type MyStringType = string; const str = 'world'; let myStr: MyStringType = 'hello'; myStr = str; // string에 'world'라는 별명을 주었다. // 별 의미가 없다..
// Aliaing Union Type let person: string | number = 0; person = 'Mark'; type StringOrNumber = string | number; // StringOrNumber이라는 타입별칭을 붙였다. // 별칭 붙일 때는 앞에 type + 별칭 let another: StringOrNumber = 0; another = 'Anna'; /* 1. 유니온 타입은 A 도 가능하고 B 도 가능한 타입 2. 길게 쓰는걸 짧게 */
// Aliaing Tuple let person: [string, number] = ['Mark', 35]; type PersonTuple = [string, number]; let another: PersonTuple = ['Anna', 24]; /* 1. 튜플 타입에 별칭을 줘서 여러군데서 사용할 수 있게 한다. */

3-1. Type alias와 Interface와 차이점

보통은 interface와 class등을 자주 사용하기 때문에 alias 쓰는 타이밍이 초반에는 많이 없다. interface를 사용하다가 굳이 사용할 필요가 없는 순간에 alias를 쓰면 된다.

  1. 오류 메세지 타입스크립트가 컴파일을 시도할때 오류가 나올때, Alias라는 이름으로 알려주지 않고 타입 자체로 알려준다.
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. 상속을 받을 수는 있지만 상속을 할 수는 없다.
type PersonAlias = { name: string; age: number; }; // type alias interface IPerson extends PersonAlias {} // 가능 let ip: IPerson = { name: 'Mark', age: 35, }; class PersonImpl implements PersonAlias { name: string; age: number; hello() { console.log('안녕하세요'); } } // PersonImpl라는 클래스는 PersonAlias라는 인터페이스를 구현하겠다. let pi: PersonImpl = new PersonImpl(); pi.hello(); class PersonChild extends PersonAlias {} // 불가능

참고링크

  1. http://gdthink.blogspot.kr/2006/06/extends%EC%99%80-implements%EC%9D%98-%EC%B0%A8%EC%9D%B4.html 
  2. http://poiemaweb.com/typeScript-interface 
Previous5/ interface
Next3/ Typescript_기본 데이터 타입

Related

© 2025 Felix