typescript 関数を定義する

typescript 関数を定義する

typescriptで、関数を定義するサンプルコード記述してます。typescriptのバージョンはVersion 4.1.2となります。

環境

  • 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