Home > database >  How does typescript fit this method
How does typescript fit this method

Time:01-16

test.js

const testList = [1, 2, 2, 4, 5, 2, 4, 2, 4, 5, 5, 6, 7, 7, 8, 8, 8, 1, 4, 1, 1];
const lastIndex = testList.findLastIndex((e:number) => e === 100);
// Property 'findLastIndex' does not exist on type 'number[]'. Did you mean 'findIndex'?ts(2551)
// lib.es2015.core.d.ts(43, 5): 'findIndex' is declared here.

tsconfig.json

...
"target": "ES6",           
...

Does the findLastIndex method need any settings of ts?

CodePudding user response:

The findLast() array method and the findLastIndex() array method are currently, as of 2023-01-15, part of a proposal which has reached Stage 4 of the TC39 process. Thus they are not currently in any released version of ECMAScript, but they are in the ESNext version and will therefore appear in ES2023.

For TypeScript, microsoft/TypeScript#48829 was filed to support these additions. They were implemented in microsoft/TypeScript#49636 which was just merged into the TS main branch on 2023-01-13 (two days ago). So no currently released version of TypeScript supports them, but they are in the typescript@next nightly version and will be released with TypeScript 5.0.

So, for now, if you want to access these methods without adding your own declarations for them, you should use the nightly version of TypeScript with your --target set to "ESNext" (or maybe "ES2023" if the option is available).

Playground link to code, TS5.0-dev with ESNext target

CodePudding user response:

let lastIndex = -1;
for (let i = testList.length - 1; i >= 0; i--) {
    if (testList[i] === 100) {
        lastIndex = i;
        break;
    }
}
console.log(lastIndex); // -1 if 100 is not in the list, otherwise the last index of 100

CodePudding user response:

Seems like it's a typescript problem, there are some discussions about it:

I think this answer is what you're looking for:

  • Related