Any does array.method get error on typescript?

Viewed 212
Question: This function determines if all the elements in array are subset of each other 


// SECTION Toy_03
Array.prototype.isSubsetOf = function (array: string[]): boolean {
  if (!array.length) return true;
    return this.every((el: string): boolean => array.includes(el));

example output// 
let a = ['commit', 'push'];
a.isSubsetOf(['commit', 'rebase', 'push', 'blame']); // true
};

I am converting couple of my javascript code into typescript in order to practice typescript. I am assuming I am doing everything correct since all the array I am supposed to receive through this function is array of string and that it should return boolean value.

Then I get two erros like below:

inSubsetOf : Property 'isSubsetOf' does not exist on type 'any[]'.ts(2339)

includes : Property 'includes' does not exist on type 'string[]'.ts(2339)

I am trying to understand as to why I am getting this error, and found out that these two are both object prototype methods. Is there something I am doing wrong syntactically?

Please advise.

1 Answers

In order to have includes on your Arrays you need to modify your tsconfig:

{
  "compilerOptions": {
    "lib": [
       "dom",
       "es7"
    ]
  }
}

To have your custom isSubsetOf function available on the global Array prototype, you have to explicitly add the types:

interface Array<T> {
  isSubsetOf(arr: T[]): boolean;
}

Or globally:

declare global {
  interface Array<T> {
    isSubsetOf(arr: T[]): boolean;
  }
}

Playground

Related