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

前端 未结 5 717
长发绾君心
长发绾君心 2020-11-28 09:49

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

ES6+ allows this simple/clean approach

[{"id":1}, {"id":-2}         


        
相关标签:
5条回答
  • 2020-11-28 09:59

    Part One - Polyfill

    For browsers that haven't implemented it, a polyfill for array.find. Courtesy of MDN.

    if (!Array.prototype.find) {
      Array.prototype.find = function(predicate) {
        if (this == null) {
          throw new TypeError('Array.prototype.find called on null or undefined');
        }
        if (typeof predicate !== 'function') {
          throw new TypeError('predicate must be a function');
        }
        var list = Object(this);
        var length = list.length >>> 0;
        var thisArg = arguments[1];
        var value;
    
        for (var i = 0; i < length; i++) {
          value = list[i];
          if (predicate.call(thisArg, value, i, list)) {
            return value;
          }
        }
        return undefined;
      };
    }
    

    Part Two - Interface

    You need to extend the open Array interface to include the find method.

    interface Array<T> {
        find(predicate: (search: T) => boolean) : T;
    }
    

    When this arrives in TypeScript, you'll get a warning from the compiler that will remind you to delete this.

    Part Three - Use it

    The variable x will have the expected type... { id: number }

    var x = [{ "id": 1 }, { "id": -2 }, { "id": 3 }].find(myObj => myObj.id < 0);
    
    0 讨论(0)
  • 2020-11-28 10:01

    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.

    0 讨论(0)
  • 2020-11-28 10:07

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

    {
        "compilerOptions": {
            "experimentalDecorators": true,
            "module": "commonjs", 
            "target": "es5"
        }
        ...
    
    0 讨论(0)
  • 2020-11-28 10:12

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

    {
      "compilerOptions": {
        "target": "es6",
        ...
    
    0 讨论(0)
  • 2020-11-28 10:22

    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)
        );
    
    0 讨论(0)
提交回复
热议问题