ceth
ceth

Reputation: 45295

Type of Underscore expression

Why this expression

_.chain(this.entityTypeConnections)
 .filter(function (con:app.domain.EntityTypeConnection) { return con.typeId == typeId; })
 .size()
 .value()

have a type EntityTypeConnection[], but not the number?

I need to compare this expression with zero ( > 0 ) and get the error:

error TS2365: Operator '>' cannot be applied to types 'EntityTypeConnection[]' and 'number'

I am trying to check if there is an element in the collection with certain typeId.

Upvotes: 0

Views: 70

Answers (1)

Michael Rose
Michael Rose

Reputation: 7820

So basically I assume that you cannot use size() in a typed context. Checking the .d.ts files for underscore shows the its return type to be _Chain<T> which would be _Chain<EntityTypeConnection[] in your case - obviously this is wrong (run it in plain javascript and you will get your number).

Alternatives

Get the value ("unchain") and just call .length on the array:

let size = _.chain(this.entityTypeConnections)
    .filter(function (con:app.domain.EntityTypeConnection) { return con.typeId == typeId; })
    .value()
    .length;

If you want to check the presence of an item with the given typeId, you can also just use:

let hasItem = !!_.findWhere(this.entityTypeConnections, {
    typeId: typeId
});

Upvotes: 1

Related Questions