Search code examples
javascriptangulartypescriptany

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


I have a class object:

groupNameData: GroupNameData = new GroupNameData();

and I have an any object

 groupNameDatas: any;

Assignment 1 (class = any)

I just assigned the class object values to any object, like

this.groupNameDatas = this.groupNameData;

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

Assignment 2 (any = class)

Now I have reversed the assignment, like

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

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


Solution

  • 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?

    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.