如何在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中的对象,则可以这样做:

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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值