あいつの日誌β

働きながら旅しています。

TypeScript で Promise を使った例

compileOptions で target を es6 にしておけば import {Promise} from 'es6-promise' は不要らしい

準備

% mkdir practice-ts-pattern && cd $_
% npm init --yes

create tsling.json:

% tslint --init
% cat << EOF > tsconfig.json
{
  "version": "1.7.5",
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6"
  }
}
EOF

create dtsm.json and typings:

% dtsm init
% dtsm install node --save

create .gitignore

% cat << EOF > .gitignore
node_modules
typings
EOF

add and commit them.

% git init && git add . && git commit -m 'initial commit'

書いてみる

ES6 で書くとこうなる

'use strict';

const getPromise = (delay) => {

  return new Promise((resolve, reject) => {

    setTimeout(() => {
      resolve('ok');
    }, delay || 3000);

    setTimeout(() => {
      reject('ng');
    }, 1000);
  }); 
}

getPromise(500).then(console.log).catch(console.log);
getPromise(1500).then(console.log).catch(console.log);

実行結果

% node promise.js
ok
ng

TypeScript で書くとこうなる

/// <reference path="./typings/bundle.d.ts" />

const getPromise: (delay: number) => Promise<{}> = (delay) => {

  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('ok');
    }, delay || 3000);

    setTimeout(() => {
      reject('ng');
    }, 1000);
  }); 
};

getPromise(500).then(console.log).catch(console.log);
getPromise(1500).then(console.log).catch(console.log);

interface を定義する場合はこう書く

/// <reference path="./typings/bundle.d.ts" />

interface ThisInterface {
  (delay: number): Promise<{}>;
}

const getPromise: ThisINterface = (delay) => {

  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('ok');
    }, delay || 3000);

    setTimeout(() => {
      reject('ng');
    }, 1000);
  }); 
};

getPromise(500).then(console.log).catch(console.log);
getPromise(1500).then(console.log).catch(console.log);

実行結果

ok
ng