0.はじめに
TypeScriptをCoffeeScript風に書けるCivetのメモ書き。
公式ページはこちら。
※英語のページですので注意。
1.準備
下記ページを参考に動作環境を整えていきましょう。
・プレイグラウンド
・インストール
npm i -g @danielx/civet
・実行
civet source.civet ...args...
2.ハローワールド
先頭の"civet coffeeCompat"
ディレクティブの指定で互換モードに。
"civet coffeeCompat"
print = (value) ->
console.log value
return
print "ハローワールド!"
var print;
print = function (value) {
console.log(value);
return;
};
print("ハローワールド!");
おもむろにオンラインのコード実行環境のwandboxに張り付けて見ると、、、なんということでしょう(汗
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 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
が残ってる気がしますが...
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
が消えましたね!
function println(value) {
console.log(value);
}
println("暗黙的なリターンの解除");
また、let
/const
修飾子は.=
/:=
のように代入演算子で指定出来ます。
4.おわりに
気が付いたら日本語に対応していた!と思って勢いで記事を書いておりますが、誤りなどありましたらご指摘いただけると助かります。
と書きつつ、TypeScriptに変換後に変数名の重複がありエラーになっていたのは確認不足でした。ごめんなさい。
他にもパイプやオペレーター、関数のオーバーロード等々沢山書くことがありそうですが、一旦ここで指を止めます。
最後まで読んでいただきありがとうございますm(_ _)m