如何在TypeScript中為對象動態分配屬性?


本文翻譯自: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中的對象,則可以這樣做:

  1.  
    var obj = {};
  2.  
    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. 但是,這將起作用。

  1.  
    var s = {};
  2.  
    s[ 'prop'] = true;

#3樓

您可以添加此聲明以使警告靜音。

declare var obj: any;


#4樓

Or all in one go: 或一勞永逸:

  1.  
    var obj:any = {}
  2.  
    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: 所以像這樣的東西仍然是類型安全的:

  1.  
    interface IFoo{
  2.  
    bar: string;
  3.  
    baz: string;
  4.  
    boo: string;
  5.  
    }
  6.  
     
  7.  
    // How I tend to intialize
  8.  
    var foo:IFoo = <any>{};
  9.  
     
  10.  
    foo.bar = "asdf";
  11.  
    foo.baz = "boo";
  12.  
    foo.boo = "boo";
  13.  
     
  14.  
    // the following is an error,
  15.  
    // so you haven't lost type safety
  16.  
    foo.bar = 123;

Alternatively you can mark these properties as optional: 另外,您可以將這些屬性標記為可選:

  1.  
    interface IFoo{
  2.  
    bar?:string;
  3.  
    baz?:string;
  4.  
    boo?:string;
  5.  
    }
  6.  
     
  7.  
    // Now your simple initialization works
  8.  
    var foo:IFoo = {};

Try it online 在線嘗試


#6樓

Store any new property on any kind of object by typecasting it to 'any': 將任何新屬性存儲在任何類型的對象上,方法是將其類型轉換為“ any”:

  1.  
    var extend = <any>myObject;
  2.  
    extend.NewProperty = anotherObject;

Later on you can retrieve it by casting your extended object back to 'any': 稍后,您可以通過將擴展對象轉換回'any'來檢索它:

  1.  
    var extendedObject = <any>myObject;
  2.  
    var anotherObject = <AnotherObjectType>extendedObject.NewProperty;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM