[typescript] How do I find an array item with TypeScript? (a modern, easier way)

Is there a canonical way to find an item in an array with TypeScript?

ES6+ allows this simple/clean approach

[{"id":1}, {"id":-2}, {"id":3}].find(myObj => myObj.id < 0)  // returns {"id":-2}

TypeScript implements many ES6+ features and continues to do so. It seems likely it has at least as nice a solution, so:

How can an item be found in a array using TypeScript, considering ease of use, modern best practices, and elegance via simplicity?
(restating the question slightly to seek best approaches)

Notes

  • "item" could be a JavaScript object, or almost anything else. The example above happens to be to find plain ol' native JS objects, but many scenarios exist.

  • "canonical" is just a fancy way in Computer Science (and other fields) to say "general accepted rule or standard formula" (remember everyone here didn't know that at some point)

  • This is not about new features. Any version of JS could do this. However the form to do so gets less and less appealing the farther you go back in time.

  • TypeScript roadmap for reference.

This question is related to typescript

The answer is


You could just use underscore library.

Install it:

   npm install underscore --save
   npm install @types/underscore --save-dev

Import it

   import _ = require('underscore');

Use it

    var x = _.filter(
      [{ "id": 1 }, { "id": -2 }, { "id": 3 }],
      myObj => myObj.id < 0)
    );

Playing with the tsconfig.json You can also targeting es5 like this :

{
    "compilerOptions": {
        "experimentalDecorators": true,
        "module": "commonjs", 
        "target": "es5"
    }
    ...

For some projects it's easier to set your target to es6 in your tsconfig.json.

{
  "compilerOptions": {
    "target": "es6",
    ...

If you need some es6 improvements not supported by Typescript, you can target es6 in your tsconfig and use Babel to convert your files in es5.