[英]Cast object type to another type
I have class where I set type of range
to IntervalRange
我有一个将range
类型设置为IntervalRange
export class Test {range: IntervalRange;}
then in parent class I initialize the value: 然后在父类中,我初始化值:
export class TestInitializer {
Create(){
return <Test>{
range: IntervalRange.initialize(Database.GetByName('MONTH').id};
}
InitializeElement() {
let test = <Test>JSON.parse(JSON.stringify(configuration));
return test;
}
then in my other component I use this as: 然后在其他组件中,我将其用作:
@Input() range: IntervalRange;
However on function range.getRange();
但是在函数range.getRange();
I get: ERROR TypeError: this.range.getRange is not a function
我得到: ERROR TypeError: this.range.getRange is not a function
Why is that? 这是为什么? it says range
is an Object, though it should be IntervalRange
. 它说range
是一个对象,尽管应该是IntervalRange
。
I tried writing as IntervalRange
, <IntervalRange> range
nothing worked. 我尝试编写as IntervalRange
, <IntervalRange> range
无效。 How to fix that? 如何解决?
Update: let type = typeof(this.range)
; 更新: let type = typeof(this.range)
; prints "object"
打印"object"
method: 方法:
ngOnChanges() {
if (this.range) {
let type = typeof(this.range);
let ddd = this.range.getRange(); //<----- this is where I get error
}
A typecast only casts the type. 类型转换仅强制转换类型。 Typescript doesn't exist at runtime. Typescript在运行时不存在。 Therefore if JSON.parse
doesn't return a proper Test
instance (which it won't since methods won't get serialized), it will fail at runtime. 因此,如果JSON.parse
没有返回正确的Test
实例(由于方法不会序列化,则不会返回),它将在运行时失败。 Instead of typecasting you probably want to build up a Test instance, and load the serialized data into it. 您可能不希望进行类型转换,而是要构建一个Test实例,然后将序列化的数据加载到其中。
The TypeScript "cast" ( <A>tmp
or tmp as A
) : TypeScript“广播”( <A>tmp
或tmp as A
):
any
. 进行结构类型兼容性检查→如果源数据的类型为any
则不可用。 When the data comes from an unsafe/external source, eg JSON.parse() or a WebAPI call, it's a DTO (data transfer object) , with the any
type. 当数据来自不安全/外部来源(例如JSON.parse()或WebAPI调用)时,它是DTO (数据传输对象) ,具有any
类型。 The TypeScript "cast" is unsafe too. TypeScript“ cast”也是不安全的。
To ensure the cast operation, you can use a mapping function from the DTO to the "domain model" class. 为了确保强制转换操作,可以使用从DTO到“域模型”类的映射功能。 The key point is to return a real class instance. 关键是返回真实的类实例。
Object.assign(new IntervalRange(), this.range)
(that you mentioned in a comment) satisfies this point. Object.assign(new IntervalRange(), this.range)
(您在注释中提到的)满足了这一点。 this.a = range.a; this.b = range.b; ...)
使用“逐字段映射”可以使我们更加严格: this.a = range.a; this.b = range.b; ...)
this.a = range.a; this.b = range.b; ...)
this.a = range.a; this.b = range.b; ...)
. this.a = range.a; this.b = range.b; ...)
。 Both options are better encaspulated in a function: the class constructor, a static factory method in the class, an external function in the same module. 这两个选项最好都包含在函数中:类构造函数,类中的静态工厂方法,同一模块中的外部函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.