如果我想在Javascript中以编程方式将一个属性分配给一个对象,我会这样做:
var obj = {};
obj.prop = "value";
但在TypeScript中,这会产生一个错误:
属性“prop”在类型为“{}”的值上不存在
我应该如何在TypeScript中分配任何新属性给对象?
如果我想在Javascript中以编程方式将一个属性分配给一个对象,我会这样做:
var obj = {};
obj.prop = "value";
但在TypeScript中,这会产生一个错误:
属性“prop”在类型为“{}”的值上不存在
我应该如何在TypeScript中分配任何新属性给对象?
当前回答
通过将任何类型的对象类型转换为'any'来存储任何新属性:
var extend = <any>myObject;
extend.NewProperty = anotherObject;
稍后,你可以通过将扩展对象转换回'any'来检索它:
var extendedObject = <any>myObject;
var anotherObject = <AnotherObjectType>extendedObject.NewProperty;
其他回答
当对象具有特定类型时,此解决方案非常有用。比如从其他源获取对象时。
let user: User = new User();
(user as any).otherProperty = 'hello';
//user did not lose its type here.
我在尝试对作为状态存储的对象进行部分更新时遇到了这个问题。
type State = {
foo: string;
bar: string;
baz: string;
};
const newState = { foo: 'abc' };
if (someCondition) {
newState.bar = 'xyz'
}
setState(newState);
在这种情况下,最好的解决方案是使用Partial<T>。方法使所提供类型上的所有属性都是可选的。令牌。在更具体的SO主题中阅读更多关于使类型上的所有属性都是可选的。
以下是我如何用Partial<T>解决它:
type State = {
foo: string;
bar: string;
baz: string;
};
const newState: Partial<State> = { foo: 'abc' };
if (someCondition) {
newState.bar = 'xyz';
}
setState(newState);
这与fregante在他们的回答中描述的类似,但我想为这个特定的用例描绘一个更清晰的画面(这在前端应用程序中很常见)。
为了保证类型是Object(即键值对),使用:
const obj: {[x: string]: any} = {}
obj.prop = 'cool beans'
你可以用这个:
this.model = Object.assign(this.model, { newProp: 0 });
或者一气呵成:
var obj:any = {}
obj.prop = 5;