0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

node index.tsが成功したので調べてみた

Last updated at Posted at 2025-02-08

きっかけ

https://qiita.com/hirokidaichi/items/27c757d92b6915e8ecf7#%E7%BF%92%E6%85%A3%E3%81%AE%E5%8A%9B
この記事を読んでTypeScriptをVsCode上で実行することに興味を持ちました。

普段Chrome拡張機能の開発を行っているのですが、ビルド→拡張機能再読み込み、Webサイト再読み込み→開発者ツールでブレークポイント設定→値を確認という開発サイクルをとっており、効率の向上ができると思いました。

調査

vscode上でTSファイルを実行するために、ts-nodetscというコマンドをインストールする必要があることを知りました。

ts-nodeは直接TSファイルの実行ができます。 
ts-node index.ts
index.tsの中身のconsole.logが実行されたことを確認できました。

tscはTSファイルをJSファイルにコンパイルします。
tsc index.ts
index.jsが生成されることを確認できました。
node index.js
console.logが実行されたことを確認できました。

疑問

試しにnode index.tsをしてみました。
node上ではTSファイルの実行ができないはずなので、エラーを確認したかったです。
しかし、index.tsの中身のconsole.logが実行されました。

確認したこと

env | grep NODE環境変数を見てもnode でts-nodeを参照しているわけではないです。
・package.jsonも確認しましたが、npm init -yしてから何もインストールしていないので初期状態です。

{
  "name": "20250208_node",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

・npm list -g
グローバルインストールもしてないです。

/Users/hogehoge/.nvm/versions/node/v16.20.2/lib
├── corepack@0.17.0
└── npm@8.19.4

解決

・TypeScriptの機能を使ったコードを書いてみる

// index.ts
interface User {
    name: string;
    age: number;
}

const user: User = {
    name: "Test",
    age: 20
};

console.log(user);

スクリーンショット 2025-02-08 12.40.03.png

失敗しました。これが原因のようです。
node index.tsとしても書かれているコードが純粋なJSとして解釈できるものだったら実行されるようです。
識別子とは関係なく、ファイルの中身を JavaScript として解釈しようとすることがわかり勉強になりました。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?