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

前端 未结 3 1184
感情败类
感情败类 2021-01-11 17:19

I have a class object:

groupNameData: GroupNameData = new GroupNameData();

and I have an any object

 groupNam         


        
3条回答
  •  不思量自难忘°
    2021-01-11 18:24

    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.

提交回复
热议问题