golangの日記

Go言語を中心にプログラミングについてのブログ

TypeScript オブジェクト(連想配列)

typescript.png


TypeScript オブジェクト(連想配列)について





目次



連想配列の定義


キーと型が決まっていて後から追加しない場合は以下のように定義する

let o: {
    name: string,
    age: number,
} = {
    name : "Tanaka",
    age : 32
};


後から追加する場合は以下のように定義する

let o: {[key: string]: number};

// 定義のみの場合は o = {}; で初期化しないとエラーになる
o = {};

o['foo'] = 100;
o['bar'] = 200;
o['baz'] = 300;

console.log(o); // { foo: 100, bar: 200, baz: 300 }



interface


interface を連想配列として使う

interface Dict {
    [key: string]: number;
}

let d: Dict = {};
d['foo']    = 100;
d['bar']    = 200;
d['baz']    = 300;


JavaScript にトランスパイルするとただのオブジェクト

var d = {};
d['foo'] = 100;
d['bar'] = 200;
d['baz'] = 300;


interface を連想配列として使うのは type で型を定義するのと同じ

type Dict = {
    [key: string]: number;
};

let d: Dict = {};
d['foo'] = 100;
d['bar'] = 200;
d['baz'] = 300;



class


class も連想配列として使うことができる

class Dict {
    [key: string]: number;
}

const d  = new Dict();
d['foo'] = 100;
d['bar'] = 200;
d['baz'] = 300;


トランスパイル後

var Dict = /** @class */ (function () {
    function Dict() {    }
    return Dict;
}());

var d = new Dict();
d['foo'] = 100;
d['bar'] = 200;
d['baz'] = 300;



TypeScriptの型はゆるい


strict オプションを指定しても以下の a, b, c, d は関数の引数として通る


class A {
    [key: string]: number;
};

interface B {
    [key: string]: number;
}

type C = {
    [key: string]: number;
};

const a: A  = new A();
const b: B  = {};
const c: C  = {};
const d: {} = {};

for (const v of [a, b, c, d]) {
    (function(vv: A) {
        console.log(vv);
    })(v);
}