gpt4 book ai didi

javascript - 在 Typescript 中过滤现有对象属性

转载 作者:行者123 更新时间:2023-12-03 00:20:28 25 4
gpt4 key购买 nike

我在 typescript 中有一个 any 对象,我需要对其进行整形,以便它对于给定的接口(interface)有效。

我需要一种方法来创建新对象,以清除不属于类定义的属性,并添加缺少的属性。

代码示例可以是:

interface ImyInterface {
a: string;
b: string;
c?:string;
};

let myObject = {
a: "myString",
d: "other value"
};

我的问题是:有没有办法转换/过滤 myObject 使其符合接口(interface) ImyInterface 定义,并转换为此

console.log (JSON.stringify(objectA));
> {a: 'myString', b: null}

最佳答案

可能有一个更好的方法,但是我突然想到这个方法是有效的:

    let otherObject: ImyInterface = { a: null, b: null };
let x: ImyInterface = { ...otherObject, ...myObject };

第一行定义所需接口(interface)的对象。

第二行定义了所需接口(interface)的新对象,并将 otherObject 中的所有属性复制到该对象中,然后将 myObject 中符合该接口(interface)的任何属性复制到该对象中.

注意:如果您尝试这样做:

let x: ImyInterface = { ...myObject };

您将看到一条错误,指出缺少接口(interface)的某些属性。因此,首先要创建一个“完整”对象(在我的示例中为 otherObject)。

关于javascript - 在 Typescript 中过滤现有对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54333219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com