2
2

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の基本構文一覧

Posted at

1. HelloWorld

console.log('Hello World!');

2. 変数宣言

// 文字列
let message: string = 'Hello TypeScript';
// 数字
const number: number = 42;
// 小数もnumber
const pi: number = 3.14159;
// 論理値
const bool: boolean = true;

3. 分岐

if文

let score = 90;

if (score > 80) {
    console.log('素晴らしい!');
} else if (score > 60) {
    console.log('頑張りましたね!');
} else {
    console.log('より良い結果を目指しましょう。');
}

switch文

let color = 'red';

switch (color) {
    case 'red':
        console.log('止まれ!');
        break;
    case 'yellow':
        console.log('注意!');
        break;
    case 'green':
        console.log('進め!');
        break;
    default:
        console.log('無効な色です。');
}

三項演算子

let isAuthenticated = true;
console.log(isAuthenticated ? 'ログイン済み' : 'ログインしてください');

4. 繰り返し

for (let i: number = 0; i < 5; i++) {
    console.log(i);
}

5. 関数

function greet(name: string): string {
    return 'Hello, ' + name;
}

console.log(greet('TypeScript'));

アロー関数

const greetArrow = (name: string) => `Hello, ${name}`;

console.log(greetArrow('TypeScript'));

6. クラスとオブジェクト

class Person {
    name: string;

    constructor(name: string) {
        this.name = name;
    }

    greet(): void {
        console.log('Hello, ' + this.name);
    }
}

const person = new Person('John');
person.greet();

7. エラー処理

try {
    throw new Error('Something went wrong');
} catch (e: any) {
    console.error(e.message);
}

8. リスト(配列)

let numbers: number[] = [1, 2, 3, 4, 5];
console.log(numbers);

9. 辞書(連想配列)

// key が String、value が String ある事を宣言している
let person1: { [key: string]: string } = {
    name: 'John',
    age: '30' // String
};
console.log(person1.name);

10. ファイル入出力

import {readFile, writeFile} from 'fs/promises';

async function writeFileExample() {
    await writeFile('example.txt', 'Hello TypeScript');
    console.log('File written');
}

async function readFileExample() {
    const content = await readFile('example.txt', 'utf8');
    console.log(content);
}

writeFileExample().then(() => readFileExample());
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?