[Google Apps Script] Using TypeScript in a Clasp Project

TypeScript を clasp プロジェクトで利用します。

## インストール

`@types/google-apps-script` を利用します。

> – [Develop Apps Script using TypeScript  |  Apps Script  |  Google Developers](https://developers.google.com/apps-script/guides/typescript)
> – [DefinitelyTyped/DefinitelyTyped: The repository for high quality TypeScript type definitions.](https://github.com/DefinitelyTyped/DefinitelyTyped)

“`prettyprinted
% yarn global add @google/clasp
% yarn add @types/google-apps-script
% clasp –version
2.2.1
“`

`clasp create` か `clasp clone` でプロジェクトファイルを用意します。

> – [clasp 入門 | deadwood](https://www.d-wood.com/blog/2019/07/30_11378.html)

ファイル拡張子を `.ts` に変更します。

“`prettyprinted
% mv Code.js Code.ts
“`

ファイル構成は下記のようになっています。

“`prettyprinted
.
├── Code.ts
├── appsscript.json
├── node_modules
├── package.json
└── yarn.lock

1 directory, 4 files
“`

## clasp push だけでトランスパイルされる

`Code.ts` の内容をサンプルコードに書き換えます。

“`TypeScript:Code.ts
const greeter = (person: string) => {
return `Hello, ${person}!`;
};

function myFunction() {
let user = “Grant”;
Logger.log(greeter(user));
}
“`

`clasp push` を実行します。
ブラウザ上のスクリプトエディタを確認するとトランスパイルされた結果が表示されます。

“`JavaScript:Code.gs
// Compiled using ts2gas 3.4.4 (TypeScript 3.5.3)
var exports = exports || {};
var module = module || { exports: exports };
var greeter = function (person) {
return “Hello, ” + person + “!”;
};
function myFunction() {
var user = “Grant”;
Logger.log(greeter(user));
}
“`

`clasp push –watch` オプションを利用すると、ファイルの変更を検知して自動で `clasp push` してくれます。

## 補遺

TypeScript

> – [TypeScript in 5 minutes · TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)
> – [まずは5分で学ぶ!TypeScriptことはじめ | DevelopersIO](https://dev.classmethod.jp/client-side/javascript/typescript-tutorial/)

TypeScript on ESLint

> – [TypeScript on ESLint の未来 – Qiita](https://qiita.com/mysticatea/items/aaf677928e965abe093d)
> – [typescript-eslint/typescript-eslint: Monorepo for all the tooling which enables ESLint to support TypeScript](https://github.com/typescript-eslint/typescript-eslint)
> – [@typescript-eslint ことはじめ – teppeis blog](https://teppeis.hatenablog.com/entry/2019/02/typescript-eslint)