LoginSignup
0
0

More than 5 years have passed since last update.

TypeScriptでの外部リソース操作について

Posted at

外部リソース操作が発生するコード周りは以下のような感じにしています。

リソースクラス

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

interface Window {
    webApiBaseUrl: string;
}

module Resource {

    //WebApiサーバーのUrl
    var urlBase = window.webApiBaseUrl;

    export class Parson {

        constructor(
            public id: string,
            public name: string,
            public address: { zip: string; address: string; tel1: string; tel2: string}) { }

        static get(): JQueryPromise<Array<Parson>> {
            return $.getJSON(urlBase + "/master/parson")
                .then((data: Array<any>, textStatus, jqXHR) => {
                    //データ取得してから戻り値オブジェクト作るところは、
                    //どうしてもAny値を扱う必要があるので、インテリセンスに頼れない。
                    var d = $.Deferred();
                    var parsons = new Array<Parson>(data.length);
                    for (var i = 0; i < data.length; i++) {
                        parsons[i] = new Parson(
                            data[i].id,
                            data[i].name,
                            {
                                zip :  data[i].zip,
                                address : data[i].address,
                                tel1 : data[i].tel1,
                                tel2 : data[i].tel2
                            });
                    }
                    return d.resolve(parsons).promise();
                });
        }
    }
}

リソースクラスの利用側

コード補完(私はVisualStudio使っていますが、他環境でも同じ感じになると思います。)で型情報表示されています。安全にプログラミングが出来そうです。

20150223_resource01.png

0
0
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
0
0