TypeScript assign()でオブジェクトにキーと値の要素を追加するサンプル
環境
Windows 11 Pro 64bit
TypeScript 4.4.4
構文
Object.assign(obj, {key1: value1, key2: value2, ・・・}); //{}内の要素を追加する
第1引数に対象のオブジェクト、第2引数に追加する要素をまとめたオブジェクトを指定します。
使用例
type Numbers = {
[key: string]: number
}
const res: Numbers = {
"key1": 1,
"key2": 2,
}
Object.assign(res, {"key6": 36, "key7": 67});
console.log(res);
type Numbers = {
[key: string]: number
}
const res: Numbers = {
"key1": 1,
"key2": 2,
}
Object.assign(res, {"key6": 36, "key7": 67});
console.log(res);
type Numbers = { [key: string]: number } const res: Numbers = { "key1": 1, "key2": 2, } Object.assign(res, {"key6": 36, "key7": 67}); console.log(res);
実行結果
[LOG]: {
"key1": 1,
"key2": 2,
"key6": 36,
"key7": 67
}
[LOG]: {
"key1": 1,
"key2": 2,
"key6": 36,
"key7": 67
}
[LOG]: { "key1": 1, "key2": 2, "key6": 36, "key7": 67 }