如果我想在Javascript中以编程方式将一个属性分配给一个对象,我会这样做:
var obj = {};
obj.prop = "value";
但在TypeScript中,这会产生一个错误:
属性“prop”在类型为“{}”的值上不存在
我应该如何在TypeScript中分配任何新属性给对象?
如果我想在Javascript中以编程方式将一个属性分配给一个对象,我会这样做:
var obj = {};
obj.prop = "value";
但在TypeScript中,这会产生一个错误:
属性“prop”在类型为“{}”的值上不存在
我应该如何在TypeScript中分配任何新属性给对象?
当前回答
如果你正在使用Typescript,你可能想要使用类型安全;在这种情况下,naked Object和'any'是相反的。
最好不要使用Object或{},而是使用一些命名类型;或者您可能正在使用具有特定类型的API,您需要使用自己的字段进行扩展。我发现这个方法很有效:
class Given { ... } // API specified fields; or maybe it's just Object {}
interface PropAble extends Given {
props?: string; // you can cast any Given to this and set .props
// '?' indicates that the field is optional
}
let g:Given = getTheGivenObject();
(g as PropAble).props = "value for my new field";
// to avoid constantly casting:
let k = getTheGivenObject() as PropAble;
k.props = "value for props";
其他回答
为Angular扩展@jmvtrinidad解决方案,
当使用已经存在的类型化对象时,这是添加新属性的方法。
let user: User = new User();
(user as any).otherProperty = 'hello';
//user did not lose its type here.
现在如果你想在html端使用otherProperty,这是你需要的:
<div *ngIf="$any(user).otherProperty">
...
...
</div>
Angular编译器将$any()视为转换为any类型,就像TypeScript中使用a <any>或任意类型转换一样。
尽管编译器抱怨它仍然应该按照你的要求输出它。然而,这是可行的。
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
通过将任何类型的对象类型转换为'any'来存储任何新属性:
var extend = <any>myObject;
extend.NewProperty = anotherObject;
稍后,你可以通过将扩展对象转换回'any'来检索它:
var extendedObject = <any>myObject;
var anotherObject = <AnotherObjectType>extendedObject.NewProperty;
案例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