Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get Array.prototype.includes to work in Typescript 2.0

Tags:

typescript

I am using typescript@next (version 2.1.0-dev.20160812 to be specific).

I am getting errors when trying to use Arrays.prototype.includes.

For instance this code

let myItems: Array<string>;
let exists: boolean = myItems.includes('blah');

Generates the following error:

Property 'includes' does not exist on type 'string[]'.at line 124 col 26

This is my tsconfig.json:

{
  "compileOnSave": true,
  "compilerOptions": {
    "module": "es6",
    "target": "es6",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "noImplicitAny": true,
    "sourceMap": true,
    "outDir": "ts-build",
    "jsx": "preserve"
  },
  "exclude": [
    "node_modules"
  ]
}
like image 693
methodex Avatar asked Aug 15 '16 16:08

methodex


People also ask

How do I use TypeScript includes?

In TypeScript, we can use the includes() method of an array to check if an array includes a certain element or value.

How do you check if an array contains an element in TypeScript?

Use the includes() method to check if an array contains a value in TypeScript, e.g. if (arr. includes('two')) {} . The includes method will return true if the value is contained in the array and false otherwise. Copied!

How do I create an array of objects in TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!


3 Answers

I fixed this by adding lib:["es2016", "dom"] to the compiler options in tsconfig.json

like image 159
methodex Avatar answered Oct 20 '22 22:10

methodex


You can add "es2016.array.include" to the compilerOptions

like image 2
ericnielsen33 Avatar answered Oct 20 '22 22:10

ericnielsen33


I added lib:["es2017", "dom"] to compilerOptions in tsconfig.json. For more clarification, check out this github issue

like image 1
malmike21 Avatar answered Oct 20 '22 22:10

malmike21