Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...