
型を簡単に作成
型を作成する関数を作成してTypeScriptのinterfaceを作成しやすくした。
型はnumber, stringなどのよく使われているもの以外の型(Dateなど)は来ない前提で付与。
1. オブジェクトの中身を判定する型を作成
var obj = {
a: 1,
b: 'foo',
c: true,
d: '',
e: [1, 2, 3],
g: ['b', 'a', 'r'],
h: [true, false, true],
i: null,
j: undefined
};
function checkType(obj) {
var result = '';
var type = '';
var len = Object.keys(obj).length;;
var i = 0;
for (var p in obj) {
i++;
if(obj[p] === null || typeof(obj[p]) === 'undefined') {
type = 'any';
} else if(typeof(obj[p]) === 'object') {
var flag;
for(var j = 0, jl = obj[p].length - 1; j < jl; j++) {
if(typeof(obj[p][j]) !== typeof(obj[p][j+1])) {
type = 'any';
} else {
type = typeof(obj[p][j]) + '[]';
}
}
} else {
type = typeof(obj[p]);
}
result += p + ': ' + type + ';\n';
}
console.log(result);
}
checkType(obj);
2. 開発ツールのコンソール出力内容をコピー

3. interfaceにペースト
interface IObj {
a: number;
b: string;
c: boolean;
d: string;
e: number[];
g: string[];
h: boolean[];
i: any;
j: any;
}
var obj: IObj = {
a: 1,
b: 'foo',
c: true,
d: '',
e: [1, 2, 3],
g: ['b', 'a', 'r'],
h: [true, false, true],
i: null,
j: undefined
};


