为什么打字稿允许分配“任意"字样?对象类型转换为类对象? [英] Why does Typescript allow to assign an "any" object type to class object?

查看:84
本文介绍了为什么打字稿允许分配“任意"字样?对象类型转换为类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类对象:

groupNameData: GroupNameData = new GroupNameData();

,我有一个any对象

 groupNameDatas: any;

作业1(类别=任何)

我刚刚将类对象值分配给any对象,例如

this.groupNameDatas = this.groupNameData;

这意味着this.groupNameDatas(任何人)都可以接受任何类型的数据,因为它是一个any对象.

It means, this.groupNameDatas (Any) can accept any kind of data, because it's an any object.

现在我像

this.groupNameData = this.groupNameDatas;// any to class

它也像我的第一个作业示例一样工作.为什么它没有引发cannot convert implicitly "any" to "GroupNameData"之类的错误?

It's also working like my first assignment example. Why it did not throw an error like cannot convert implicitly "any" to "GroupNameData"?

推荐答案

这是预期的行为(

This is the expected behavior (docs). Hopefully this sample will clarify it:

let someObj = new MyClass();
// someObj will be of the "MyClass" type.

let anyObject : any;
// since anyObject is typed as any, it can hold any type:
anyObject = 1;
anyObject = "foo";
// including your class:
anyObject = someObj;

// so, if it can hold anything, it's expected that we can assign our custom classes to it:
someObj = anyObj;

但是打字稿如何接受将任何对象分配给类对象?

But how can typescript accept to assign any object to class object?

any类型很有趣. Typescript无法知道您的any类型变量是否包含对象的实例.没什么,所以它可能是您对象的实例.

That's the fun with the any type. Typescript can't know if your any-typed variable holds an instance of your object or not. It's anything, so it could be an instance of your object.

这篇关于为什么打字稿允许分配“任意"字样?对象类型转换为类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆