您好我想推送一个现有的TypeScript中的新键值对,我尝试了下面的步骤但没有发生任何错误请帮助
profile = {"RouteID":"B76F77922EF83A4EE04024921F591A6F","Name":"3019998FALCON","rName":"KILGORE REMOVED"}
let newvalue = "jzket"
profile["userID"] = newvalue
答案 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);
有用的链接: