如何在打字稿中推送一个新的键值对

时间:2018-06-06 13:53:02

标签: angular typescript ionic-framework

您好我想推送一个现有的TypeScript中的新键值对,我尝试了下面的步骤但没有发生任何错误请帮助

 profile = {"RouteID":"B76F77922EF83A4EE04024921F591A6F","Name":"3019998FALCON","rName":"KILGORE REMOVED"}

let newvalue = "jzket"
profile["userID"] = newvalue

2 个答案:

答案 0 :(得分:1)

您问题中的代码基本上是正确的,这是一个完整的工作示例:

const profile = {
    "RouteID": "B76F77922EF83A4EE04024921F591A6F",
    "Name": "3019998FALCON",
    "rName": "KILGORE REMOVED"
}

profile["userID"] = "jzket";

// Works everywhere
console.log(profile["userID"]);

// Works, but violates the type information available here
console.log(profile.userID);

您会注意到类型系统会抱怨后一种用法,因为userID不属于profile推断类型的一部分。

您可以坚持使用第一个示例(profile['userID'])或提供​​更多类型信息:

interface Profile {
    RouteID: string;
    Name: string;
    rName: string;
    userID?: string;
}

const profile: Profile = {
    "RouteID": "B76F77922EF83A4EE04024921F591A6F",
    "Name": "3019998FALCON",
    "rName": "KILGORE REMOVED"
}

profile["userID"] = "jzket";

// Works everywhere
console.log(profile["userID"]);

// Works, but violates the type information available here
console.log(profile.userID);

答案 1 :(得分:0)

我完全赞同@Fenton。也许更好的方法是添加一个新的密钥 / 对:

像这样的

Object.assign

const newProfile = Object.assign(profile, { userID: "jzket" });

Spread Syntax

const newProfile = ({...profile, userID: "jzket" });

JSFiddle 示例:

const profile = {
  "ruteID":"B76F77922EF83A4EE04024921F591A6F",
  "Name":"3019998FALCON",
  "rName":"KILGORE REMOVED",
};

// With object assign
const exampleOne = Object.assign(profile, { userID: "jzket" });

// With spread syntax
const exampleTwo = ({...profile, userID: "jzket" })

console.log(exampleOne);
console.log(exampleTwo);

有用的链接:

Spread Syntax

Object Assign