[英]How to initialize object with generic type in TypeScript?
I tried to do this like: 我试图这样做:
export class MapperObject<V> {
public obj: V = {};
}
It does not work. 这是行不通的。 Further I need to fill object like: 此外,我需要像这样填充对象:
this.obj[key] = "1";
Without initialization it invokes an error. 如果没有初始化,它将调用一个错误。
The short answer is you can't do this in a type-safe way, because you don't know the fields of V
that are required. 简短的答案是您不能以类型安全的方式执行此操作,因为您不知道所需的V
字段。 You can force initialization by using a type assertion, but it's not exactly safe: 您可以使用类型断言强制进行初始化,但这并不完全安全:
export class MapperObject<V> {
public obj: V = {} as any;
}
let m = new MapperObject<{ requiredProp: string }>();
m.obj.requiredProp // undefined even though it is required
The safe solution is to have a constructor that requires the passing of a default for obj
: 安全的解决方案是让构造函数需要传递obj
的默认值:
export class MapperObject<V> {
constructor(public obj: V) {}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.