뽀삐릿
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 타입스크립트 톺아보기 ## Why TypeScript? - 타입스크립트는 타입이 입혀진 자바스크립트. 자바스크립트의 슈퍼셋. 일종의 확장된 언어. - 즉, **타입스크립트는 자바스크립트의 모든 기능을 포함하면서 정적 타입을 지원하는 언어다.** ### 정적 타입 언어 vs 동적 타입 언어 | 정적 타입 언어 | 동적 타입 언어 | | -------- | -------- | | 타입에 대한 고민을 하지 않아도 되므로 배우기 쉽다 | 변수를 선언할 때마다 타입을 고민해야 하므로 진입 장벽이 높다 | 코드의 양이 적을때 생산량이 높다 | 코드의 양이 많을 때 동적 타입 언어에 비해 생산성이 높다. | 타입 오류가 런타임 시 발견된다. | 타입 오류가 컴파일 시 발견된다. ## **장점** **1. 에러에 대한 사전 방지 기능** 좀더 정확하게 데이터의 모습을 보고 판단할 수 있게 한다. (ex) address는 문자가 아니라 객체) 우리가 타입을 잘못 알거나 오타를 발생시키면 type에러가 발생하게 된다. 타입스크립트를 사용하면 이런 부분들을 상당히 보완할 수 있다. 리액트의 경우 tsx파일을 javascript로 변환하는 트랜스파일링이 필요하다. 이때 변환하는 과정에서 에러를 잡을 수 있다. **2. 코드 가이드 및 자동 완성(개발 생산성 향상)** result 가 숫자라고 명시했기 때문에, number가 쓸수 있는 메소드들을 바로 확인하고 사용할 수 있다!! **3. 정적 타입을 지원해준다**** typescript를 사용하는 가장 큰 이유 중 하나는 정적타입을 지원한다는 것. 이말은 **컴파일 단계에서 오류를 포착** 할 수 있고 명시적인 정적타입 지정은 개발자의 의도를 명확하게 코드로 기술할 수 있다. 이는 **코드의 가독성을 높이고 예측할 수 있게 하며 디버깅을 쉽게 한다.** ## **단점** - 번거로움 : 초반 세팅이 필요하다. 컴파일을 위한 옵션도 설정해야 한다. ## TypeScript는 오류를 어느 단계에서 포착하는가? 타입스크립트는 컴파일 단계에서 AST를 만들어 결과 코드를 내놓기 전에 타입 확인 과정을 거칩니다. (타입 검사기를 사용한다) - `typechecker`: 코드의 타입 안전성을 검증하는 프로그램 타입스크립트의 마법은 **타입 확인 과정**에서 발생하며, 타입 확인 덕분에 프로그래머의 기대대로 프로그램이 실행될 수 있으며 실수를 방지할 수 있다. 전체적인 타입스크립트 컴파일 과정 은 다음과 같다. ![https://media.vlpt.us/images/ggob_2/post/be680c2c-123b-473a-9cf0-4906ca18fb58/TSC.png](https://media.vlpt.us/images/ggob_2/post/be680c2c-123b-473a-9cf0-4906ca18fb58/TSC.png) 1~3은 **TSC**가 수행하며, 4~6은 **브라우저, NodeJS, 기타 자바스크립트 엔진 등에서 수행**한다. 과정 1~2에서는 소스 코드에 사용된 타입을 사용하지만, 과정 3에서는 이용하지 않는다. **즉, TSC가 타입스크립트 코드를 자바스크립트 코드로 컴파일할 때는 개발자가 사용한 타입을 확인하지 않는다.** 개발자가 코드에 기입한 타입 정보는 최종적으로 만들어지는 프로그램에 아무런 영향을 주지 않으며, 단지 타입을 확인하는 데만 쓰인다. #### 🤨 트랜스파일링 컴파일링 인터프리팅 ## 기본타입 ``` Boolean Number String Object Array Tuple Enum Any Void Null Undefined Never ``` ### null, undefined - 타입스크립트에서 타입으로 존재함 - 다른 타입과 함께 유니온 타입으로 정의할 때 사용된다. ```javascript= // By default null and undefined are subtypes of all other types. // That means you can assign null and undefined to something like number. let num: number; // 초기화 안했을 때 undefined 허용 ``` ### unknown, any - unknown : 어떤 데이터가 담길 지 알 수 없음 - any : 어떤 값이든 담을 수 있음 - 타입 정의가 안 된 외부 패키지 사용하는 경우 ### void, never - void : 어떤 값도 리턴하지 않는 함수의 리턴 타입 - never : 함수의 끝에 절대 도달하지 않는 경우 (ex. throw Error()) ### object - 원시값이 아닌 어떤 object 값이든 할당 가능 (배열도 ..) - 속성 정보를 포함해서 타입을 정의하기 위해선 인터페이스를 사용해야 한다. ## 이넘(Enum) - **특정 값들의 집합**을 의미하는 자료형 - 열거형 타입의 각 원소는 값으로 사용 가능하며, 타입으로도 사용 가능 - 숫자형 이넘은 auto increasement - 숫자형 이넘에선 값과 원소 이름이 양방향 매핑됨 - 문자형 이넘에선 단방향 매핑됨 - 열거형 타입은 객체이기 때문에 컴파일 후에도 남아있게 된다. 따라서 번들 파일의 크기가 불필요하게 커질 수 있다. 열거형 타입의 객체에 접근하지 않는다면 굳이 컴파일 후에 객체로 남겨 놓을 필요는 없다. - 상수(const) 열거형 타입을 사용하면 컴파일 결과에 열거형 타입의 객체를 남겨 놓지 않을 수 있다. ```tsx // 숫자형 이넘 enum Fruit { Apple, // 0 Banana = 5, // 5 apple2 // 5 + 1 } const var1: Fruit.Apple = asa const var2 : any = Fruit.Banana console.log(Fruit[5]) // Banana console.log(Fruit.Banana) // 5 console.log(Fruit[`Banana`]) //5 // 문자형 이넘 enum Direction { Up = "UP", Down = "DOWN", Left = "LEFT", Right = "RIGHT", } ``` 타입스크립트에서는 문자형 이넘과 숫자형 이넘을 지원한다. [TypeScript enum을 사용하지 않는 게 좋은 이유를 Tree-shaking 관점에서 소개합니다](https://engineering.linecorp.com/ko/blog/typescript-enum-tree-shaking/) 🤔 함수 오버로딩, 메소드에 타입 추가하기 등 (교재에 나온 설명들) ## 타입 별칭 (Type Aliases) 특정 타입이나 인터페이스를 **참조**할 수 있는 타입 변수를 의미한다. 즉, **정의된 타입에 대해 나중에 쉽게 참고할 수 있게 이름을 부여하는 것.** - 인터페이스와 사용방법은 같으나 쓰는 모습이 다르다. - 타입별칭은 사실상 어느곳에서나 쓸 수 있다. 즉, 타입을 정의할 수 있는 모든 곳에서 쓸 수 있다. - 타입 별칭은 실제로는 새 타입을 생성하지 않는다. 따라서 타입과 관련된 에러가 발생했을 시 타입 별칭을 보여주지 않고 실제 타입을 보여준다. `type Width = number | string ` - extends 안됨 ```tsx interface Animal { name: string; } interface Dog extends Animal { breed: string; } ``` - 🤔 사용 이유 (인터페이스 있는데 왜 쓰냐 🧐) ## 인터페이스 인터페이스는 **상호 간에 정의한 약속 혹은 규칙**을 의미한다. 타입스크립트에서의 인터페이스는 보통 다음과 같은 범주에 대해 약속을 정의할 수 있다. - 객체의 스펙(속성과 속성의 타입) - 함수의 파라미터 - 함수의 스펙(파라미터, 반환 타입 등) - 배열과 객체를 접근하는 방식 (readonly ..) - 클래스 [출처 : 타입스크립트 핸드북](https://joshua1988.github.io/ts/guide/interfaces.html#%EC%9D%BD%EA%B8%B0-%EC%A0%84%EC%9A%A9-%EC%86%8D%EC%84%B1) ### 특징 - javascript(ES6)가 지원하지 않는 typescript만의 특징입니다. - interface는 type이며 compile후에 사라집니다. - interface는 선언만 존재합니다. - 속성과 method는 선언할 수 있지만 접근 제한자는 설정할 수 없습니다. - interface 간에 extends를 사용하여 다중 상속이 가능합니다. ## **인터페이스 확장** 클래스와 마찬가지로 인터페이스도 인터페이스 간 확장이 가능합니다. ```tsx interface Person { name: string; } interface Developer extends Person { skill: string; } let fe = {} as Developer; fe.name = 'josh'; fe.skill = 'TypeScript'; ``` 혹은 아래와 같이 여러 인터페이스를 상속받아 사용할 수 있습니다. ```tsx interface Person { name: string; } interface Drinker { drink: string; } interface Developer extends Person { skill: string; } let fe = {} as Developer; fe.name = 'josh'; fe.skill = 'TypeScript'; fe.drink = 'Beer'; ``` 🤔 인덱스 시그니처? Indexable Types ```tsx interface a { [key] : value } ``` ```tsx interface Person{ name : string age ?: number } const p1 = { name : "조병건" job : "학생" } // o const p3 : Person = p1 // x const p4 : Person = { name : "조병건" job : "학생" } ``` ## 클래스 ### 추상 클래스 ## **Abstract Class** 추상 클래스(Abstract Class)는 인터페이스와 비슷한 역할을 하면서도 조금 다른 특징을 갖고 있습니다. 추상 클래스는 **특정 클래스의 상속 대상이 되는 클래스**이며 좀 더 상위 레벨에서 속성, 메서드의 모양을 정의합니다. ```tsx abstract class Developer { abstract coding(): void; // 'abstract'가 붙으면 상속 받은 클래스에서 무조건 구현해야 함 drink(): void { console.log('drink sth'); } } class FrontEndDeveloper extends Developer { coding(): void { // Developer 클래스를 상속 받은 클래스에서 무조건 정의해야 하는 메서드 console.log('develop web'); } design(): void { console.log('design web'); } } const dev = new Developer(); // error: cannot create an instance of an abstract class const josh = new FrontEndDeveloper(); josh.coding(); // develop web josh.drink(); // drink sth josh.design(); // design web ``` ### 추상 클래스를 이용한 공통 기능 정의 추상 클래스는 구현 메서드와 추상 메서드가 동시에 존재할 수 있습니다. - 구현 메서드 - 실제 구현 내용을 포함한 메서드 - 추상 메서드 - 선언만 된 메서드 추상 클래스는 단독으로 객체를 생성할 수 없고, 추상 클래스를 상속하고 구현 내용을 추가하는 자식 클래스를 통해 객체를 생성해야 합니다. ```tsx abstract class 추상클래스 { abstract 추상메서드(); abstract 추상멤버변수: string; public 구현메서드(): void { 공통적으로 사용할 로직을 추가함 로직에서 필요 시 추상 메서드를 호출해 구현 클래스의 메서드가 호출되게 함 this.추상메서드(); } } ``` 추상 클래스에 선언한 추상 메서드는 오버라이딩해서 자식 클래스에서 반드시 구현해서 사용해야 합니다. ### 추상클래스 vs 인터페이스 **인터페이스** - 선언만 존재한다. - 사용목적 : 어떤 '행동'에 대한 명세일 뿐, 그 자체가 상속관계를 나타내주진 않는다. - 인터페이스는 멤버 변수와 멤버 메서드를 선언할 수 있지만 접근 제한자는 설정할 수 없다. - 클래스의 구현 세부 정보를 포함할 수 없다. **추상클래스** - 선언과 구현이 모두 존재한다. - 사용목적 : 객체지향 프로그래밍에서 상속관계를 나타내기 위함. - 클래스의 멤버에 대한 구현 세부 정보를 포함할 수 있다. - 접근제한자 설정 가능 🤔 타입스크립트의 추상클래스 왜 쓰냐.. # 타입 호환성 > 정적 타입 언어는 컴파일 타임에 타입 호환성을 통해 호환되지 않는 타입을 찾아내는 것이다. - 타입 A가 타입 B에 할당 가능하다 = 타입 A는 타입 B의 서브타입이다. - 구조적 타이핑 - 코드 구조 관점에서 타입이 서로 호환되는지의 여부를 판단하는 것 - 값 자체의 타입보다는 값이 가진 내부 구조에 기반 # 제네릭 - 타입을 마치 함수의 파라미터처럼 사용하는 것이다. - 장점 - 재사용성이 높다 - 하나의 타입뿐만 아니라 여러 타입에 적용할 수 있는 컴포넌트를 만들 수 있다 - extends로 제네릭 타입 제한 가능 ㅇㅇ # 맵드타입 - 기존에 정의되어 있는 타입을 새로운 타입으로 변환해 주는 문법. - 기존 인터페이스의 모든 속성을 선택속성이나 읽기전용으로 만들 때 주로 사용된다. # 타입 추론 [* 타입추론 - 타입스크립트 핸드북](https://joshua1988.github.io/ts/guide/type-inference.html#%ED%83%80%EC%9E%85-%EC%B6%94%EB%A1%A0%EC%9D%98-%EA%B8%B0%EB%B3%B8) - 타입스크립트가 코드를 해석해 나가는 동작을 타입추론이라고 한다. - 변수를 선언하거나 초기화 할 때 타입이 추론된다. - 타입 추론 장점 - 정적 타입 언어에서는 모든 변수나 파라미터, 프로퍼티 등의 타입을 모두 선언해야하기 때문에, 타입 추론 같은 기능이 필요없다. 하지만 TypeScript 에서는 모든 변수에 항상 타입을 선언할 필요가 없으므로 컴파일러가 타입 추론을 잘해주기만 해도 타입 선언 비용이 상당히 줄어든다. - 문맥상의 타이핑 ```tsx window.onmousedown = function(mouseEvent) { console.log(mouseEvent.button); //<- OK console.log(mouseEvent.kangaroo); //<- Error! }; ``` - Best common type - 배열에 여러 자료형이 섞여 있을 때 그것들을 포함할 수 있는 타입으로 설정 (ex. union) - 타입 단언 - TypeScript 의 타입 추론 기능은 매우 강력하지만 어쩔 수 없는 한계가 존재한다. 타입 단언은 TypeScript 컴파일러가 타입을 실제 런타임에 존재할 변수의 타입과 다르게 추론하거나 너무 보수적으로 추론하는 경우에 프로그래머가 수동으로 컴파일러한테 특정 변수에 대해 타입 힌트를 주는 것이다. - `as` 키워드 사용 - 타입 단언 vs 타입 캐스팅 - 타입 단언은 타입을 변경한다는 사실 때문에 타입 캐스팅과 비슷하게 느껴질 수 있다. 타입 단언이 타입 캐스팅이라고 불리지 않는 이유는 런타임에 영향을 미치지 않기 때문이다. 타입 캐스팅은 컴파일타임과 런타임에서 모두 타입을 변경시키지만 타입 단언은 오직 컴파일타임에서만 타입을 변경시킨다. [* 타입 추론 vs 타입 단언](https://hyunseob.github.io/2017/12/12/typescript-type-inteference-and-type-assertion/) # 타입 가드 [* 타입 가드 - 타입스크립트 Deep Dive ](https://aerocode.net/327) [* 타입 가드에 대한 좀더 쉬운 설명 ](https://radlohead.gitbook.io/typescript-deep-dive/type-system/typeguard) - 조건문을 이용해 타입의 범위를 좁히는 기능이다. - 타입 가드는 이러한 런타임에서의 타입 체크를 컴파일러에게 알려주는 기능이다. - 타입스크립트의 타입 체크는 Only 컴파일 시간에 이루어진다. 컴파일 시간에는 비교적 엄격하게 타입체크를 하는편이지만, 그 외에는 타입체크가 거의 없다시피 하기때문에, 런타임시에는 진짜 그 타입이 맞는지 체크하는 것이 어렵다. ```tsx interface Args { n: number; s: string; } let invaildArgs: any = { num: 3, str: "str" }; let fakeArgs: Args = invaildArgs; console.log(fakeArgs.n, fakeArgs.s); ``` - 위의 코드에서 fakeArgs는 실제로는 Args 인터페이스를 구현하지 않았기 때문에, console.log에서 undefined를 출력할 것. 이러한 사건, 사고가 발생하는 것을 막기위해, 진짜 이 타입이 맞아?라고 확인하는 작업을 타입 가드type guard라고 한다. - 타입스크립트의 공식 문서에는 사용자 정의 타입 가드 (User Define Type Guard)를 만들어서 사용할 것을 권고하고 있다. ```tsx // EX. function ArgsGuard(target: Args): boolean { if (target == undefined) return false; if (target.n == undefined) return false; if (target.s == undefined) return false; if (new Object(target.n).constructor != Number) return false; if (new Object(target.s).constructor != String) return false; return true; } ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully