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

Jay*_*esh 5 typescript ionic-framework angular

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

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

let newvalue = "jzket"
profile["userID"] = newvalue
Run Code Online (Sandbox Code Playgroud)

Fen*_*ton 6

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

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);
Run Code Online (Sandbox Code Playgroud)

您会注意到类型系统会抱怨后一种用法,因为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);
Run Code Online (Sandbox Code Playgroud)