Avatar ·

How to check if an array contains a string in TypeScript?

Hello! I'm new to TypeScript (and JavaScript in general), and I have a problem.\n\nI have an array of strings, and I need to check if it contains a specific value. It seems like it should be simple, but I can't figure out how to do it correctly in TypeScript, especially with strict typing.\n\nHere's an example of my code:\n\n```typescript\nconst fruits: string[] = ['apple', 'banana', 'orange'];\nconst search: string = 'banana';\n\n// I tried this:\nif (fruits.indexOf(search) !== -1) {\n console.log('Found!');\n}\n\n// And this:\nif (fruits.includes(search)) {\n console.log('Found!');\n}\n```\n\nBoth options work, but I've heard that `includes` is a more modern method. However, I'm not sure which one is preferable in TypeScript, and whether there are any pitfalls.