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

5

18

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

Logarithmic answered 12/4, 2017 at 14:59 Comment(9)
this.groupNameDatas could be a GroupNameData, since it's typed as any it could be of any type.Direct
I think you misunderstand my question. Actually my question is why class object is accept any object? does make sense?Logarithmic
@LeonardoChaia , kindly see my question one more time .Logarithmic
If you understand the purpose of types, this seems kinda obvious. You want a banana. How bout I just give you what's in this magic box that has something random in it. Let's hope it's a bananaPuppet
Reason please for the downvote?Logarithmic
@peeskillet I don't think this is obvious if you have been using a statically typed language like C# where assigning to a specific type variable from object always requires a cast. No reason to be so condescending.Nescience
@Nescience I think I misread the question. I Think I read "Why did it not throw" as "Why did it throw", hence my comment.Puppet
@peeskillet Doesn't make sense. Your banana example answers "Why did it not throw" question.Nescience
@Nescience Maybe it should be "You want a banana to make a banana split.. I give you a box... but you need a banana" Maybe there should be an emphasis that you need a banana. It can't be anything else. If you don't give me a banana, I will reject it. Maybe the example wasn't clear. I guess that's why it got so many up-votes :-)Puppet
D
7

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.

Direct answered 12/4, 2017 at 15:15 Comment(7)
Typescript can't know if your any-typed variable holds an instance of your object or not , So it's totally override my class object??Logarithmic
Well, that's how Javascript works. If you can do it on Javascript, you can do it on Typescript.Direct
SO is it same as let and var?Logarithmic
If you can do it on Javascript, you can do it on Typescript That's why I asked that?Logarithmic
Sorry, still not understanding the comparison. Maybe this could be another SO question.Direct
I think he asked the question because he expected the language (in strict mode) to require us to explicitly cast the any to the specific type, but it doesn'tTheroid
Typescript now supports the unknown type which can be used if you want explicit casting.Direct
S
6

If you look at the official documentation, it clearly says that with "any" all compile time checks are ignored.

Relevant snippet from the docs:

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;
Sociolinguistics answered 12/4, 2017 at 15:18 Comment(0)
R
2

TypeScript needs a different way of thinking from a traditional statically type language. In languages like C# or Java the compilar gives a type error unless the programer has provided enough information to make clear to the compiler it should not give a type error. In Typescript the compiler only gives a type error if the programer has provided enough information for the compiler to know the types are not valid.

The use of Any takes information away from the compiler.

Typescript was created to allow the incremental addition of type information with as many bugs in the program being found at compile as the type information allows. It can be thought of as a "super lint" that takes advantage of any type information that is provided.

Over the years Typescript has moved closer to what people (like me) who are used to strict compile time type checked languages expect, but it great stenth is that it still, "fits in" well with Javascript.

Ricardo answered 19/7, 2020 at 18:12 Comment(0)
L
2

You can read about unknown - this is the type-safe counterpart of the any type.

Here is a link with the differences.

Lorusso answered 13/7, 2021 at 10:58 Comment(1)
Thank you!! This should be the correct answer! People coming from other typed languages like c# expect asigning any to a type to fail like "Object" to "Specific type" fails. Didn't know that the "Object" equivalent in Typescript is the "unknown" so i used "any" the wrong way,Twocolor
K
1

Not sure the original question was really answered, so here is an additional example.

Typescript will let you assign anything that could potentially be a match, so:

  • you can't assign a string to a number...
  • ...but if you declare that string as any – no one complains!

More poetically: Not only can you assign anything to any, you can also assign anyto anything.

Code below in TS Playground


class Test {
    constructor() {
        // "My type is number"
        // NO ERROR
        const oneAsNumber: number = 1;
        this.myFunction(oneAsNumber); 
        
        // "My type is string"
        // !!ERROR: Argument of type 'string' is not assignable to parameter of type 'number'.
        const oneAsString: string = '1';
        this.myFunction(oneAsString); 

        // "My type is string"
        // NO ERROR
        const oneAsStringButDisguisedAsAny: any = '1';
        this.myFunction(oneAsStringButDisguisedAsAny);
    }

    myFunction(n: number) {
        console.log(`My type is ${typeof(n)}`);
    }    
}

new Test();
Kwang answered 2/6, 2023 at 5:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.