I have a class object:
groupNameData: GroupNameData = new GroupNameData();
and I have an any
object
groupNameDatas: 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.
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"
?
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.