zoukankan      html  css  js  c++  java
  • 如何在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;
  • 相关阅读:
    AutoMapper 模型转换
    HttpClient Post请求
    C#根据中文description获取enum枚举值
    SQLserver链接字符串MySql链接字符串区别
    EF+Linq分组 多条件
    netcore导入 取Excel中的数据做操作
    net core文件流导出文件
    V-IF 使用包含判断条件
    Vue 使用mounted 或created自动调用函数,遇到的第一个问题 this 指针指向
    VUE 属性绑定
  • 原文地址:https://www.cnblogs.com/makai/p/13935453.html
Copyright © 2011-2022 走看看