LoginSignup
96
68

More than 5 years have passed since last update.

TypeScriptで関数を型にする

Last updated at Posted at 2015-12-31

Typescriptの型として、

「number」「string」「boolean」などとありますが、

実は、関数も型にできます!

sample.ts
var function1: (arg1: number, arg2: string) => boolean;

こんな感じ。

(引数名:型, 引数名:型 .....) => 戻り値

戻り値がないときは、voidを指定できます。

どんなときにつかうの?

コールバック引数を使いたい

callback.ts
function progressA(callback: (msg: string) => void) {
  callback("hoge");
}

progressA(msg => {
  console.log(msg);
});

関数を配列とする

array.ts
var fnArray:Array<(msg: string) => void> = [];
fnArray.push(msg => {
  alert(msg);
});
fnArray.push(msg => {
  console.log(msg);
});
fnArray.forEach(i => {
  // 関数だから呼び出せる
  i("Hello, TypeScript!");
});

AddEventListenerの引数にも!

lib.d.tsを見てみると、

lib.d.ts
addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;

引数listenerの型にも使われています!

TypeScript楽しい!奥深い!

96
68
7

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
96
68