https://qiita.com/mangano-ito/items/75e65071c9c482ddc335
node でさっくりと TypeScript を実行したいときに、babel なり webpack なりで transpile して実行するのは不便です。しかも型が考慮されなくなってしまいますね。
そういうときは ts-node を使うことで、バベってファイルを生成してから食わせずとも、そのまま実行できるので手軽です。型も考慮されます。
さっくりと依存を追加します:
tsconfig.json
もついでに生成しておきます:
> ./node_modules/.bin/tsc --init
message TS6071: Successfully created a tsconfig.json file.
試しに適当なコードを書いてみます:
src/main.ts
const main = () => {
console.log('It works!');
};
main();
動かしてみます:
> ./node_modules/.bin/ts-node src/main.ts
It works!
いい感じにすぐ実行されました。
もちろん型が誤っている場合もきちんとエラーになりますし、元のファイルの情報が表示されます:
src/main.ts
const main = (str: string) => {
console.log('It works!');
};
main(1111);
TSError: ⨯ Unable to compile TypeScript:
src/main.ts:5:6 - error TS2345: Argument of type '1111' is not assignable to parameter of type 'string'.
5 main(1111);
~~~~
import some from '../../a/b.ts'
とかになってややこしいので、パスのエイリアスを登録しておくことが結構あると思います:
tsconfig.json
{
"compilerOptions": {
// ...
"baseUrl": "./",
"paths": {
"#/*": ["src/*"]
},
// ...
}}