宮原将太
    • 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
    # -01-02- イントロダクション ###### tags: `TypeScript` # TypeScriptを使うことで受ける恩恵 - ミスをチェックしたりすることでプログラムをより安全に - リファクタリングを容易に - 単体テストのほぼ半分を不要に - 自分自身または今後のエンジニアのための文書として機能 - プログラマーとしての生産性が2倍 - ~~通りの向こう側の可愛いバリスタとのデートが実現できる~~ # 型安全性(type safety) 型を使って、プログラムが不正な事をしないように防ぐこと  **JavaScript** - 不正なことをしようとしてもエラーを出さずに、(親切に、静かに)プログラマーの意図を解釈して最善な値を返してくれる親切な言語 ```javascript= // JavaScript 3 + [] // 文字列の3と評価 const object = {}; object.foo; // undefined(未定義)と評価 function hoge(number) { return number/2; }; hoge("foo"); // NaNと評価 ``` **TypeScript** - 不正なことをしようとすると即座にエラーを起こし、型警察としての職務を全うすることに執着した頑固な言語 ```typescript= // TypeScript 3 + [] // error:数字と文字列の演算はできないよ! const object = {}; object.foo; // error:objectはfooなんて持ってないよ! function hoge(number) { return number/2; }; hoge("foo"); // error:hoge()の引数は数値型が欲しい! ``` ## エラーを出すタイミング **JavaScript** - プログラムを実行したとき **TypeScript** - エディターで記述したとき # コンパイラー **Java等のコンパイル実行** 1. プログラムがASTへと解釈される 2. ASTがバイトコードにコンパイルされる 3. バイトコードがランタイムによって評価される **TypeScriptのコンパイル実行** 1. プログラムがTypeScript ASTへと解釈される 2. TypeScript ASTがJavaScriptコードにコンパイルされる 3. バイトコードがランタイムによって評価される # 型チェッカー(typechecker) コードが型安全であることを検証する特別なプログラム コンパイル時に型チェックを行うことで以下のことが確実になる - 作成したプログラムが期待通りに動作してくれる - 明らかなミスが存在しない - ~~通りの向こう側の可愛いバリスタが後で電話してくれる~~ # 型システム(type system) プログラマーが作成したプログラムに型を割り当てるために型チェッカーが使用するルールの集まり ## アノテーション 型が何かを明示的にTypeScriptに伝えるためにはアノテーションを使用する > アノテーションとは「値:型」という形式を取り、型チェッカーに「ここに値が見えるだろ?その横にあるのがその値の型だよ」と伝える ```typescript= // TypeScript const a: number = 1; // aはnumberです const b: string = "foo"; // bはstringです const c: boolean[] = [true, false]; // cはbooleanの配列です ``` 明示的に型を宣言しなくてもTypeScriptは型を推論してくれる(これをTypeScriptの魔法と呼ぶらしい) ```typescript= // TypeScript const a = 1; // aはnumberです const b = "foo"; // bはstringです const c = [true, false]; // cはbooleanの配列です ``` ## TypeScript⚔JavaScript | 型システムの特徴 | JavaScript | TypeScript | | -------- | -------- | -------- | | 型はどのようにバインドされるか?| 動的 | 静的 | | 型は自動的に変換されるか? | はい | いいえ(多くの場合) | | 型はいつチェックされるか? | 実行時 | コンパイル時 | | エラーはいつ表面化するか? | 実行時(多くの場合) | コンパイル時(多くの場合) | ## 1. 型はどのようにバインドされるか? JavaScriptの「型が動的にバインドされる」とは、型を知るためにはまず実行しないと型について解釈するまでに辿り着けないということ TypeScriptは型付けしていないプログラムでさえ、実行前に(エディタ上などで)型推論を行いミスを見つけることができる **TypeScriptは漸進的型付き言語** - プログラム内の全てのものの型がわかっている場合にTypeScriptは最も力を発揮するが、**プログラムをコンパイルするためには必ずしも全ての型がわかっている必要はない** ## 2. 型は自動的に変換されるか? JavaScriptは弱く型付けされた言語なので、最善の結果を返せるように一連のルールを適用してプログラマーの意図を理解しようとしてくれる ```javascript= const foo1 = 3 + [1]; consle.log(foo1); // "31" ``` JavaScriptはこのプログラムを、 1. 3が数値、[1]が配列であることを理解する 2. 演算子+を使っているので、その2つを連結したいのだろうと理解する 3. 3は数値だが暗黙的に文字列に変換し、”3”とする 4. [1]は配列だが暗黙的に文字列に変換し、”1”とする 5. それらの文字を連結し、”31”として値を返してくれる また上記のフローを明示的にプログラミングすることができる ```javascript= // JavaScript const foo2 = (3).toString() + [1].toString(); consle.log(foo2); // "31" ``` **しかし、TypeScriptはこの暗黙的に変換する作業をしないのである** ```typescript= // TypeScript const hoge1 = 3 + [1]; consle.log(hoge1); // error:数値型と配列型だから違うモノ同士だよ const hoge2 = (3).toString() + [1].toString(); consle.log(hoge2); // "31" ``` 正しそうに見えないことをするとエラーを吐き、型を明示的にしてあげることでTypeScriptは手を引いてくれる JavaScriptが行う暗黙的な型の変換は、突き止めの難しいエラーやバグを生む温床になりかねない 要するに、**型を変換する必要がある場合は明示的に書きましょうというお話でした** ## 3. 型はいつチェックされるか? **JavaScript** - プログラム実行時にチェック **TypeScript** - コードを書いた時に型推論を行いチェック ## 4. エラーはいつ表面化するか? **JavaScript** - プログラム実行時にエラーをthrow **TypeScript** - コードをコンパイルした際にエラーをthrow # TypeScriptを書くために ## tsconfig.json すべてのTypeScriptプロジェクトは、そのルートディレクトリにtsconfig.jsonと呼ばれるプロジェクトで扱うTypeScriptファイルについて設定を書かなければいけない ```json= { "compilerOptions": { "lib": ["es2015"], "module": "commonjs", "outDir": "dist", "sourceMap": true, "strict": true, "target": "es2015" }, "include": [ "src" ] } ``` ## tsconfig.jsonのオプション | オプション | 説明 | 記述例 | | ------- | -------- | -------- | | include | TSCがTypeScriptファイルを見つけるために、どのフォルダーを探すべきか | src | | lib | コードを実行する環境にどのAPIが存在しているとTSCが想定すべきか | es2015 | | module | TSCがコードをどのモジュールシステムにコンパイルするべきか | commonjs | | outDir | 生成するJavaScriptコードをTSCがどのフォルダに格納するべきか | dist, out | | strict | 厳密にコードをチェックするか | true | | target | TSCがコードをどのJavaScriptバージョンにコンパイルするか | es3, es5, es2015, es2016 |

    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