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 を作成します。

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

    1. @typescript-eslint/parser @typescript-eslint/eslint-plugin をインストールします。

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

      ...,
      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();
      ...
    }