如果我想在Javascript中以编程方式将一个属性分配给一个对象,我会这样做:

var obj = {};
obj.prop = "value";

但在TypeScript中,这会产生一个错误:

属性“prop”在类型为“{}”的值上不存在

我应该如何在TypeScript中分配任何新属性给对象?


当前回答

尽管编译器抱怨它仍然应该按照你的要求输出它。然而,这是可行的。

const s = {};
s['prop'] = true;

其他回答

试试这个:

export interface QueryParams {
    page?: number,
    limit?: number,
    name?: string,
    sort?: string,
    direction?: string
}

然后使用它

const query = {
    name: 'abc'
}
query.page = 1

在TypeScript中动态地为对象分配属性。

你只需要像这样使用typescript接口:

interface IValue {
    prop1: string;
    prop2: string;
}

interface IType {
    [code: string]: IValue;
}

你可以这样使用它

var obj: IType = {};
obj['code1'] = { 
    prop1: 'prop 1 value', 
    prop2: 'prop 2 value' 
};

你可以用这个:

this.model = Object.assign(this.model, { newProp: 0 });

只需这样做,您就可以添加或使用任何属性。(我使用的typescript版本为“typescript”:“~4.5.5”)

let contextItem = {} as any;

现在,您可以添加任何属性并在任何地方使用它。就像

contextItem.studentName = "kushal";

之后你可以这样使用它:

console.log(contextItem.studentName);

晚不过,简单回答

let prop = 'name';
let value = 'sampath';
this.obj = {
   ...this.obj,
   [prop]: value
};