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

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

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

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

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


当前回答

若要保留先前的类型,请将对象临时转换为any

  var obj = {}
  (<any>obj).prop = 5;

新的动态属性只有在使用强制转换时才可用:

  var a = obj.prop; ==> Will generate a compiler error
  var b = (<any>obj).prop; ==> Will assign 5 to b with no error;

其他回答

我很惊讶没有一个答案引用Object。赋值,因为这是我在考虑JavaScript中的“组合”时使用的技术。

在TypeScript中,它可以像预期的那样工作:

interface IExisting {
    userName: string
}

interface INewStuff {
    email: string
}

const existingObject: IExisting = {
    userName: "jsmith"
}

const objectWithAllProps: IExisting & INewStuff = Object.assign({}, existingObject, {
    email: "jsmith@someplace.com"
})

console.log(objectWithAllProps.email); // jsmith@someplace.com

优势

始终保持类型安全,因为您根本不需要使用任何类型 使用TypeScript的聚合类型(在声明objectWithAllProps类型时用&表示),这清楚地表明我们正在动态地(即动态地)组合一个新类型。

需要注意的事情

Object.assign has it's own unique aspects (that are well known to most experienced JS devs) that should be considered when writing TypeScript. It can be used in a mutable fashion, or an immutable manner (I demonstrate the immutable way above, which means that existingObject stays untouched and therefore doesn't have an email property. For most functional-style programmers, that's a good thing since the result is the only new change). Object.assign works the best when you have flatter objects. If you are combining two nested objects that contain nullable properties, you can end up overwriting truthy values with undefined. If you watch out for the order of the Object.assign arguments, you should be fine.

案例1:

var car = {type: "BMW", model: "i8", color: "white"};
car['owner'] = "ibrahim"; // You can add a property:

案例2:

var car:any = {type: "BMW", model: "i8", color: "white"};
car.owner = "ibrahim"; // You can set a property: use any type

这是Object的一个特殊版本。赋值,它会在每次属性更改时自动调整变量类型。不需要额外的变量、类型断言、显式类型或对象副本:

function assign<T, U>(target: T, source: U): asserts target is T & U {
    Object.assign(target, source)
}

const obj = {};
assign(obj, { prop1: "foo" })
//  const obj now has type { prop1: string; }
obj.prop1 // string
assign(obj, { prop2: 42 })
//  const obj now has type { prop1: string; prop2: number; }
obj.prop2 // number

//  const obj: { prop1: "foo", prop2: 42 }

注意:示例使用TS 3.7断言函数。与Object.assign不同,assign的返回类型是void。

最简单的是

const obj = <any>{};
obj.prop1 = "value";
obj.prop2 = "another value"

最好的做法是使用安全输入,我建议你:

interface customObject extends MyObject {
   newProp: string;
   newProp2: number;
}