在打字稿中使用与号运算符

问题描述

如何创建 AccessGroup 类型的变量

std::unordered_set/std::unordered_map

我认为我们可以这样做

hashing

但是它给出了一个错误,因为将某些东西分配给 toJSON() 是强制性的,并且不知道这一点,除了如果我没有错的话 & 就像一个交叉点一样工作

谁能举例说明如何为变量定义 toJSON()

解决方法

你只需像在课堂上一样实现它。这意味着您返回一个基于运行该方法的对象的对象,以及一个额外的属性。

看起来像 { ...this,extraProp: 'whatever' }

declare class AccessGroup {
    id: number;
    active: boolean;
    display_name: string;
    toJSON(): this & {
        access_group_features: any;
    };
}

let x: AccessGroup = {
    id: 123,active: true,display_name: 'Testing 123',toJSON() {
        return {
            ...this,toJSON: this.toJSON,// Make typescript happy
            access_group_features: 'Test'
        }
    }
}

只要您像 x.toJSON() 这样调用该方法,那么 this 将是 x 对象,一切都会正常工作。

您可能已经注意到,我需要显式传入 toJSON 方法,因为它没有包含在 ...this 中。我相信这是因为在一个类中方法是不可枚举的。方法存储在类原型中,因为它们不会因实例而改变。这意味着打字稿不相信 toJSON 将成为 { ...this }

的属性

至少我认为,这个有点棘手。

Playground


但是在 toJSON() 的返回中使用任何函数可能也不正确。所以你可能根本不想包含它。

如果您将类型更改为:

toJSON(): Omit<this,'toJSON'> & {
    access_group_features: any;
};

那么你可以省略方法:

toJSON() {
    return { ...this,access_group_features: 'Test' }
}

Playground


但是创建一个普通对象来实现带有方法的类接口并不理想。如果你能真正上完那门课,然后再做new AccessGroup(),你的生活可能会轻松得多。

,

对@Alex Wayne 上面的回答做了一个小小的改动。

原始问题在 AccessGroup 中有另一个属性,称为 access_group_features,它是一个数组

declare class AccessGroup {
    id: number;
    active: boolean;
    display_name: string;
    description: string;
    access_group_features: [];
    created_at?: Date;
    created_by?: string;
    updated_at?: Date;
    updated_by?: string;
    static fromJSON(json: any): any;
    toJSON(): this & {
        access_group_features: any;
    };
}

所以 toJSON() 成员函数中的 access_group 属性也应该 属于数组类型(任何其他类型都会抛出错误,如&符号 打字稿中的运算符与属性相交,因此应该是 同类型)

toJSON(): this & {
            access_group_features: [];    /* this is probably because of strict type checking in typescript */
        };

所以创建的变量看起来像这样:

let x: AccessGroup = {
    id: 123,access_group_features:[],access_group_features: []
        }
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...