简体   繁体   中英

sort array of javascript objects, typescript error

I have two questions, one revolves around a behavior I've noticed a few times when angular-cli transpiles... and the second is a sort array question, that is triggering the #1 question.

the array I'm trying to sort looks something like this - call it an array of THINGS:

[{
    label : string,
    primary: boolean
}]

Basically a label with a 'primary' field that is boolean in nature so the values are true, false or null. I want to sort so boolean TRUEs are first, boolean FALSEs are after and NULLs are last. with the labels being alphabetical in each grouping.

I just wanted to do a simple JS array sort - no need for TS -

this.user.things.sort( function(a, b){ return b.primary > a.primary} );

So my editor is warning me of TS errors... which I ignore, because the code works.

[ts] Argument of type '(a: ThingModel, b: ThingModel) => boolean' is not assignable to parameter of type '(a: ThingModel, b: ThingModel) => number'. Type 'boolean' is not assignable to type 'number'.

I guess I'll start with Question 2. as this same error shows up at transpile time

even though this is plain JS - I like to not see squiggley lines, and red errors on transpile.

Question 2: how can I make this TS compliant?

and then, when I transpile - even though I get the error - after a few seconds - I get the "compiled successfully" message - and the site works fine.

Question 1: can someone explain to me - or point me to docs - on the transpiler and what errors are considered fatal - no-start errors, and what errors will behave like this one, where, it throws a red error - but finishes compiling anyway and the code works.??? This is more an education question than solving an error. but I'd like to understand it.

Thx.

You need to return the number not the boolean value

  this.user.things.sort(function (a, b) {
            return a.primary < b.primary ? 1 : a.primary > b.primary ? -1 : 0;
        });

Now it will not throw any warnings or errors.

You could just return the delta of the second value and the first value.

The use of comparison operators takes an implicit type conversion like the use of the minus operator.

 var array = [false, true, true, false, false, true]; array.sort((a, b) => b - a); console.log(array); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM