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

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

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

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

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


当前回答

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

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

其他回答

晚不过,简单回答

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

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

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

我倾向于把任何放在另一边,即var foo:IFoo = <任何>{};所以这样的东西仍然是类型安全的:

interface IFoo{
    bar:string;
    baz:string;
    boo:string;     
}

// How I tend to intialize 
var foo:IFoo = <any>{};

foo.bar = "asdf";
foo.baz = "boo";
foo.boo = "boo";

// the following is an error, 
// so you haven't lost type safety
foo.bar = 123; 

或者你可以将这些属性标记为可选:

interface IFoo{
    bar?:string;
    baz?:string;
    boo?:string;    
}

// Now your simple initialization works
var foo:IFoo = {};

在网上试试

你可以用这个:

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

试试这个:

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

然后使用它

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