How to check if an array contains a string in TypeScript?
Hi everyone! I'm new to TypeScript (previously wrote in plain JavaScript) and ran into a problem when checking if a string exists in an array.
I have an array of strings:
```typescript
let fruits: string[] = ['apple', 'banana', 'orange'];
```
And I need to check if it contains, for example, 'banana'. In JavaScript I would just write:
```javascript
if (fruits.indexOf('banana') !== -1) { ... }
```
or
```javascript
if (fruits.includes('banana')) { ... }
```
But in TypeScript I'm getting strange type errors. When I write:
```typescript
if (fruits.includes('banana')) {
console.log('Found!');
}
```
It works fine, but when I try to use indexOf, the compiler complains: "Argument of type 'string' is not assignable to parameter of type 'never'". I don't understand what this means at all.
No answers yet.
Log in to leave an answer
Blogs
Testing Panic in Rust: How to Write Tests for Error Situations
dyld: Library not loaded: @rpath/libswiftCore.dylib: how to fix the error
How to Determine the Type of a Variable in Swift: A Complete Guide with Code Examples
CQRS and Event Sourcing in Kotlin: Architecture for Flawless Code