本文翻译自: How do I dynamically assign properties to an object in TypeScript?
If I wanted to programatically assign a property to an object in Javascript, I would do it like this: 如果我想以编程方式将属性分配给Javascript中的对象,则可以这样做:
var obj = {};
obj.prop = "value";
But in TypeScript, this generates an error: 但是在TypeScript中,这会产生一个错误:
The property 'prop' does not exist on value of type '{}' 类型“ {}”的值不存在属性“ prop”
How am I supposed to assign any new property to an object in TypeScript? 我应该如何在TypeScript中为对象分配任何新属性?
#1楼
参考: https://stackoom.com/question/RkGB/如何在TypeScript中为对象动态分配属性
#2楼
Although the compiler complains it should still output it as you require. 尽管编译器抱怨它仍应按您的要求输出。 However, this will work. 但是,这将起作用。
var s = {};
s[ 'prop'] = true;
#3楼
您可以添加此声明以使警告静音。
declare var obj: any;
#4楼
Or all in one go: 或一劳永逸:
var obj: any = {}
obj.prop = 5;
#5楼
I tend to put any on the other side ie var foo:IFoo = <any>{}; 我倾向于把 any 放在另一边,即 var foo:IFoo = <any>{}; So something like this is still typesafe: 所以像这样的东西仍然是类型安全的:
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;
Alternatively you can mark these properties as optional: 另外,您可以将这些属性标记为可选:
interface IFoo{
bar?:string;
baz?:string;
boo?:string;
}
// Now your simple initialization works
var foo:IFoo = {};
Try it online 在线尝试
#6楼
Store any new property on any kind of object by typecasting it to 'any': 将任何新属性存储在任何类型的对象上,方法是将其类型转换为“ any”:
var extend = <any>myObject;
extend.NewProperty = anotherObject;
Later on you can retrieve it by casting your extended object back to 'any': 稍后,您可以通过将扩展对象转换回'any'来检索它:
var extendedObject = < any>myObject;
var anotherObject = <AnotherObjectType>extendedObject.NewProperty;
查看更多关于如何在TypeScript中为对象动态分配属性?的详细内容...