Why does Typescript allow you to assign "any" type of object to a class object?
I have a class object:
groupNameData: GroupNameData = new GroupNameData();
and I have an object any
groupNameDatas: any;
Purpose 1 (class = any)
I just assigned values to class objects to object any
like
this.groupNameDatas = this.groupNameData;
This means that this.groupNameDatas
(Any) can accept any data, because it is an object any
.
Assignment 2 (any = class)
Now I have canceled the assignment like
this.groupNameData = this.groupNameDatas;// any to class
It also works as my first assignment example. Why didn't it throw an error, for example cannot convert implicitly "any" to "GroupNameData"
?
source to share
This is the expected behavior ( docs ). Hopefully this sample will clarify this:
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 expected that we can assign our custom classes to it:
someObj = anyObj;
But how does typescript accept to assign some object to a class object?
It's fun with the type any
. typescript cannot know if your any
-typed variable contains an instance of your object or not. It's anything, so it could be an instance of your object.
source to share
If you look at the official documentation , it clearly states that "any" ignores all compile-time checks.
Relevant document snippet:
We may need to describe the type of variables that we do not know when writing the application. These values can be obtained from dynamic content, for example. from a user or third party library. In these cases, we want to abandon the type checking and let the value go through compile-time checks. To do this, we mark them with any type:
let notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean
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 can expect the object to play a similar role as it is in other languages. But variables of type Object allow you to assign any value to them - you cannot call arbitrary methods on them, even those that actually exist:
If you decide to use a different type, eg. number or line compile the check time and you know it isn't.
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'.
Any type is also convenient if you know some part of the type, but perhaps not all. For example, you might have an array, but the array is a mix of different types:
let list: any[] = [1, true, "free"]; list[1] = 100;
source to share