本文翻譯自: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;