为什么 Typescript 允许将 "any" 对象类型分配给 class 对象?

Why does Typescript allow to assign an "any" object type to class object?

我有一个 class 对象:

groupNameData: GroupNameData = new GroupNameData();

我有一个 any 对象

 groupNameDatas: any;

作业 1(class = 任意)

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

this.groupNameDatas = this.groupNameData;

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

作业 2(任意 = class)

现在我已经反转赋值了,像

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

它也像我的第一个作业示例一样工作。为什么它没有抛出像 cannot convert implicitly "any" to "GroupNameData"?

这样的错误

这是预期的行为 (docs)。希望这个示例能够澄清它:

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 类型的变量是否包含您的对象的实例。它可以是任何东西,因此它可以是您的对象的一个​​实例。

如果您查看 official documentation,它清楚地表明 "any" 将忽略所有编译时检查。

文档中的相关片段:

We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content, e.g. from the user or a 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the any type:

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

The any type is a powerful way to work with existing JavaScript, allowing you to gradually opt-in and opt-out of type-checking during compilation. You might expect Object to play a similar role, as it does in other languages. But variables of type Object only allow you to assign any value to them - you can’t call arbitrary methods on them, even ones that actually exist:

Should you choose to use another type e.g. number or string the compile time checks kick in and you know that its not right.

let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

The any type is also handy if you know some part of the type, but perhaps not all of it. For example, you may have an array but the array has a mix of different types:

let list: any[] = [1, true, "free"];

list[1] = 100;

TypeScript 需要一种不同于传统静态类型语言的思维方式。在 C# 或 Java 等语言中,编译器会给出类型错误,除非程序员提供了足够的信息以向编译器表明它不应该给出类型错误。在 Typescript 中,如果程序员提供了足够的信息让编译器知道类型无效,编译器只会给出类型错误。

使用 Any 会从编译器中获取信息。

创建 Typescript 是为了允许增量添加类型信息,并在编译时发现程序中的错误数量与类型信息允许的数量一样多。它可以被认为是利用所提供的任何类型信息的“超级 lint”。

多年来,Typescript 已经更接近那些习惯了严格的编译时类型检查语言的人们(比如我)所期望的,但它仍然非常“适合”Java脚本。

您可以阅读 unknown - 这是 any 类型的类型安全对应物。

这里是.