admin管理员组

文章数量:1379427

in TS 4.9.3 and angular 15 application, i have a service function isEmpty() with following snippet of code.

    static isEmpty(value: any): boolean {
        if (value === null || value === undefined || value === {} || value === []) { 
            return true;
        }
    }

and it generates This condition will always return 'false' since JavaScript pares objects by reference, not value. issue for conditions value === {} and value === [].

in TS 4.9.3 and angular 15 application, i have a service function isEmpty() with following snippet of code.

    static isEmpty(value: any): boolean {
        if (value === null || value === undefined || value === {} || value === []) { 
            return true;
        }
    }

and it generates This condition will always return 'false' since JavaScript pares objects by reference, not value. issue for conditions value === {} and value === [].

Share Improve this question edited Mar 18, 2024 at 10:31 Midhun asked Sep 20, 2023 at 6:59 MidhunMidhun 1141 silver badge10 bronze badges 1
  • 1 It means what it says: there's no point to the parison as it will always be false so your function always returns undefined. – jonrsharpe Commented Sep 20, 2023 at 7:06
Add a ment  | 

1 Answer 1

Reset to default 5

As the error states, in JavaScript objects are pared by reference. So you cannot pare object values like {} === {}. Something like this will always return false because both {} have different memory addresses.

In your case you pare an argument value to a newly created object ({}). The condition will always return false since there is no way for the objects to have the same reference. TypeScript detects this and warns you about this by showing an piler error. Also the TypeScript control-flow analysis notices that the function never returns the annotated return type boolean resulting in another piler error.

This feature was added in TypeScript 4.8 (Errors When Comparing Object and Array Literals)

[...] We believe that similar code in JavaScript is at best an early foot-gun for JavaScript developers, and at worst a bug in production code. That’s why TypeScript now disallows code like the following.

本文标签: