LoginSignup
0
0

Civetのメモ書き

Last updated at Posted at 2023-12-06

0.はじめに

TypeScriptをCoffeeScript風に書けるCivetのメモ書き。
公式ページはこちら。

※英語のページですので注意。

1.準備

下記ページを参考に動作環境を整えていきましょう。

・プレイグラウンド

・インストール
npm i -g @danielx/civet
・実行
civet source.civet ...args...

2.ハローワールド

先頭の"civet coffeeCompat"ディレクティブの指定で互換モードに。

CoffeeScript互換モード
"civet coffeeCompat"

print = (value) ->
  console.log value
  return

print "ハローワールド!"

変換後のコード(TypeScript)
var print;
print = function (value) {
  console.log(value);
  return;
};

print("ハローワールド!");

おもむろにオンラインのコード実行環境のwandboxに張り付けて見ると、、、なんということでしょう(汗

識別子'print'が重複しています、、、
prog.ts(1,5): error TS2300: Duplicate identifier 'print'.
prog.ts(2,1): error TS2539: Cannot assign to 'print' because it is not a variable.
prog.ts(7,7): error TS2554: Expected 0 arguments, but got 1.
../../opt/wandbox/typescript-4.2.4-nodejs-14.16.1/node_modules/typescript/lib/lib.dom.d.ts(19701,18): error TS2300: Duplicate identifier 'print'.

重複しているので、名前を変更するかexportしたらよいようですが、ちょっと混乱してるので一旦TypeScriptで記述します(汗

export/importを使用したコード(TypeScript)
export default function print(value) {
  console.log(value);
  return;
}

import println from "./prog";
println("ハローワールド!");

期待通りに動きました、、、TypeScriptあまり使った事無いので、こんなことになるとは思っても見ませんでした(汗

※以降printを使用したコードは、printlnに変更していきます(問題無いことを祈ります)。

CoffeeScript互換モードについては下記ページを参照。

3.型、変数の修飾子

右辺に型注釈、変数に自動でvarを付与するモード。

型注釈①
"civet autoVar"

var println = (value: any): void ->
  console.log value

println "型注釈①"

左辺にも型注釈、自動的にletを付与するモード。

型注釈②
"civet autoLet"

let println: (value: any) -> void = (value: any): void ->
  console.log value

println "型注釈②"

型エイリアスでスッキリ(constも使えます)。

型エイリアス
type Print = (value: any) -> void

const println: Print = (value) ->
  console.log value

println "型エイリアス"

トランスパイル後の関数内にreturnが残ってる気がしますが...

変換後のコード(TypeScript)
type Print = (value: any) => void;

const println: Print = function (value) {
  return console.log(value);
};

println("型エイリアス");

returnが付与される行の最後にセミコロン;を付けるとreturnが消せます(または、ディレクティブ-implicitReturnsで設定解除)。関数の定義にはfunctionも使えます。

暗黙的なリターンの解除
"civet -implicitReturns"

function println(value)
  console.log value;

println "暗黙的なリターンの解除"

returnが消えましたね!

変換後のコード(TypeScript)
function println(value) {
  console.log(value);
}

println("暗黙的なリターンの解除");

また、let/const修飾子は.=/:=のように代入演算子で指定出来ます。

4.おわりに

気が付いたら日本語に対応していた!と思って勢いで記事を書いておりますが、誤りなどありましたらご指摘いただけると助かります。

と書きつつ、TypeScriptに変換後に変数名の重複がありエラーになっていたのは確認不足でした。ごめんなさい。

他にもパイプやオペレーター、関数のオーバーロード等々沢山書くことがありそうですが、一旦ここで指を止めます。

最後まで読んでいただきありがとうございますm(_ _)m

0
0
0

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