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?

TypeScriptの構文がどうJavaScriptへ変換されるかを見る

0
Posted at

TS:手書き
JS:コンパイルで自動生成

命令

npm install -D typescript @types/node
npx tsc --init
npx tsc test.ts
node test.js

型の宣言

test.ts
const suuji: number = 25;

console.log(suuji);
test.js
var suuji = 25;
console.log(suuji);

関数戻り値を明記

test.ts
const fanc1 = (name:string): string => `name is,${name}`;

console.log(fanc1("tarou"));
test.js
var fanc1 = function (name) { return "name is,".concat(name); };
console.log(fanc1("tarou"));

Interface使用

構造体みたいに使える。

test.ts
interface User {
id: number;
name: String;
}

const admin: User = {id: 1, name: "Admin"};
console.log(admin.name);
test.js
var admin = { id: 1, name: "Admin" };
console.log(admin.name);

クラス

クラスは関数へ変換される

test.ts
class Counter {
private count:number = 0;
increment() { this.count++; }
getCount() { return this.count; };
}

const counter = new Counter();
counter.increment();
console.log(counter.getCount());
test.js
var Counter = /** @class */ (function () {
function Counter() {
this.count = 0;
}
Counter.prototype.increment = function () { this.count++; };
Counter.prototype.getCount = function () { return this.count; };
;
return Counter;
}());
var counter = new Counter();
counter.increment();
console.log(counter.getCount());

T型

test.ts
function fanc1<T>(arg: T): T {
return arg;
}

const str = fanc1<string>("Hello");
const num = fanc1<number>(42);

console.log(str);
console.log(num);
test.js
function fanc1(arg) {
return arg;
}
var str = fanc1("Hello");
var num = fanc1(42);
console.log(str);
console.log(num);

enum

test.ts
enum Direction {
Up = "UP",
Down = "DOWN",
}

const move: Direction = Direction.Up;
console.log(move)
test.js
var Direction;
(function (Direction) {
Direction["Up"] = "UP";
Direction["Down"] = "DOWN";
})(Direction || (Direction = {}));
var move = Direction.Up;
console.log(move);
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?