| TIPS |
| 変数宣言 |
[JS]
let count = 10;
count = "hello"; //
[TS]
let count: number = 10;
count = "hello"; // エラー
|
| 関数 |
[JS]
function add(a, b) {
return a + b;
}
[TS]
function add(a: number, b: number): number {
return a + b;
}
|
| オブジェクト |
[JS]
const user = {
name: "Taro",
age: 20
};
[TS]
type User = {
name: string;
age: number;
};
const user: User = {
name: "Taro",
age: 20
};
|
| クラス |
[JS]
class Person {
constructor(name) {
this.name = name;
}
}
[TS]
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
|
| 非同期処理 |
[JS]
async function getData() {
const res = await fetch(url);
}
[TS]
async function getData(): Promise {
const res = await fetch(url);
}
|
| モジュール |
[JS]
export function add() {}
[TS]
export function add(): number {}
|
| 型の拡張・合成 |
[TS]
type A = { a: number };
type B = { b: string };
type C = A & B; // 両方持つ
|