FitbitアプリケーションをTypeScriptで開発する

Posts

Fitbitで動かすアプリケーションをTypeScriptで開発する手順を説明します。

fitbit-sdk-typesを使って、JavaScriptで開発した既存のアプリケーションをTypeScriptに移行します。

動作を確認した環境

  • Node.js v12.13.1
  • @fitbit/sdk v4.0.1
  • @fitbit/sdk-cli v1.7.1

TypeScriptへの移行

  1. Fitbitアプリケーションのプロジェクト直下で、次のコマンドを実行します。

    npx fitbit-sdk-types apply-ts
    

    コマンドを実行すると、次のことが行われます。

    • package.jsondevDependenciesに「fitbit-sdk-types」が追加される
    • プロジェクト直下にtsconfig.jsonが生成される ※ 生成されない場合は、3. を参照
    • 「app」「companion」「settings」ディレクトリ以下
      • .js.tsに変更される
      • tsconfig.jsonが生成される
  2. 「app」「companion」「settings」以外にディレクトリを作っていて、.jsファイルがある場合は、手動で.tsに変更します。

  3. プロジェクト直下にtsconfig.jsonが生成されていない場合は、次の内容でtsconfig.jsonを作成します。

    tsconfig.json
    {
        "extends": "./node_modules/@fitbit/sdk/sdk-tsconfig.json"
    }
    
  4. ESLintを導入していたので、次のことも行いました。

    • @typescript-eslint/parser @typescript-eslint/eslint-pluginのインストール

      $ npm i @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
      
    • 設定ファイル(.eslintrc.js)にTypeScriptの設定の追加

      .eslintrc.js
      ...,
      plugins: ["@typescript-eslint"],
      extends: [
        "plugin:@typescript-eslint/eslint-recommended",
        "plugin:@typescript-eslint/recommended"
      ],
      ...
      

ビルド

Fitbit CLIでビルドします。Fibit CLIの使い方は、別記事を参照。

npx fitbit

fitbit$ build

もしTypeScriptのエラーがあればbuildで次のようなエラーが発生します。

[21:18:58][error][app] app/index.ts:110,13 TS2339: Property 'style' does not exist on type 'Element'.
[21:18:58][error][app] Error: Failed to compile /Users/chick-p/Works/fitbit-project/app/index.ts

移行でつまずいたところ

'style' プロパティがない

  • コード

    const el = document.getElementById("element-id");
    
  • エラー

    [21:18:58][error][app] app/index.ts:110,13 TS2339: Property 'style' does not exist on type 'Element'.
    [21:18:58][error][app] Error: Failed to compile /Users/chick-p/Works/fitbit-project/app/index.ts
    
  • 原因 document.getElementById("element-id")の戻り値の型がElementだったので、styleがないと怒られていました。

  • 解決策 GraphicsElementにキャストします。

    const el = document.getElementById("element-id") as GraphicsElement;
    

HeartRateSensorのコンストラクタでエラー

  • コード

    const hrm = new HeartRateSensor()
    
  • エラー

    [21:49:54][error][app] app/index.ts:70,18 TS2351: This expression is not constructable.
          TS2760: Not all constituents of type 'void | HeartRateSensorConstructor' are constructable.
          TS2761: Type 'void' has no construct signatures.
    [21:49:54][error][app] Error: Failed to compile /Users/chick-p/Works/fitbit-project/app/index.ts
    
  • 原因 HeartRateSensorはデバイスによっては付いてないことがあるので、存在チェックを必要とします。

  • 解決策 存在チェックをします。

    if (HeartRateSensor) {
      const hrm = new HeartRateSensor();
      ...
    }