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

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

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

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

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


当前回答

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

let contextItem = {} as any;

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

contextItem.studentName = "kushal";

之后你可以这样使用它:

console.log(contextItem.studentName);

其他回答

或者一气呵成:

  var obj:any = {}
  obj.prop = 5;

当对象具有特定类型时,此解决方案非常有用。比如从其他源获取对象时。

let user: User = new User();
(user as any).otherProperty = 'hello';
//user did not lose its type here.

晚不过,简单回答

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

可以使用展开操作符在旧对象的基础上创建新对象

interface MyObject {
    prop1: string;
}

const myObj: MyObject = {
    prop1: 'foo',
}

const newObj = {
    ...myObj,
    prop2: 'bar',
}

console.log(newObj.prop2); // 'bar'

TypeScript会推断出原始对象的所有字段,VSCode会自动补全,等等。

在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' 
};