TypeScriptで関数を作成する方法|サンプルコード付き

TypeScriptで関数を作成する方法|サンプルコード付き

TypeScriptで関数を定義する方法を解説します。functionを使った基本構文、引数や戻り値の型指定、アロー関数の書き方、オプション引数やデフォルト引数までサンプルコード付きでわかりやすく紹介します。

環境

  • OS windows10 64bit
  • typescript Version 4.1.2

関数を定義

typescriptでは、以下のように関数を定義することが可能です。

引数なし、戻り値なし

function hello(){
    console.log('hello')
}

console.log(hello()); // hello

引数あり、戻り値なし

function disp(str: string): void {
    console.log('hello' + str)
}

console.log(disp('world')); // helloworld

// voidは省略可能
function disp(str: string) {
    console.log('hello' + str)
}

引数あり、戻り値あり

function calc(num: number): number {
    return num + num;
}

console.log(calc(1)); // 2
console.log(calc(2)); // 4

引数があってもなくてもいいような場合は「?」を使用します。

function disp(str?: string) {
   (str) ? console.log('hello' + str) : console.log('hello')
}

console.log(disp()); // hello

引数にデフォルトの値を指定することも可能です。

function disp(str: string = 'world') {
   console.log('hello' + str)
}

console.log(disp()); // helloworld

無名関数やアロー関数も使用可能です。

const hoge = function(x: number, y: number) { return x + y; }

console.log(hoge(1,2)) // 3

const foo = (x: number, y: number) => { return x + y; }

console.log(foo(1,2)) // 3

参考リンク