本文翻译自: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 = {};
#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中动态为对象分配属性的方法。由于TypeScript的静态类型检查,直接赋值会引发错误。解决方案包括使用any类型、对象字面量的动态属性名和可选属性标记。通过这些技巧,开发者可以在保持类型安全的同时实现动态属性赋值。
38

被折叠的 条评论
为什么被折叠?



