-1

I have to cast this:

let selections = list.filter(obj => obj.type === "myType");

I get an error with a filter which says

filter does not exist on type 'NodeType'

I tried to follow these suggestions TypeScript casting arrays

let selections = <NodeType[]>list.filter(obj => obj.type === "myType");

but I still get the same error, I can't see how to fix this. In pure javascript, it works.

Update: thanks to answers below which makes me realize I call the right method when I tested in console and a wrong one in my code editor.

2
  • 3
    filter does not exist on type 'NodeType' that makes it sound like list is a NodeType, not an array. How was list created? Commented Oct 2, 2019 at 15:03
  • yes list is of NodeType returned by some API and I want to cast it into an array only for applying filter. In pure javascript I don't need to, it works in chrome console. Commented Oct 2, 2019 at 18:08

2 Answers 2

1

Are you sure this exact same thing works in pure JavaScript, not just something sort of like it? If list is an array which comes from the browser DOM, it's likely that really, truly it doesn't have a filter method. Those DOM arrays are only "ArrayLike", not true JavaScript arrays.

Try Array.from(list) or Array.from(list as NodeType[]) and see if that helps.

Sign up to request clarification or add additional context in comments.

3 Comments

of course it works in pure javascript: it's just an array of objects.
@user310291, my point is that "just an array" isn't always what it seems. The DOM contains arrays that aren't true JavaScript arrays. These arrays do have a length property, and they can be accessed by numeric indices, but they don't have methods like filter, map, forEach, etc. Casting doesn't, and can't, add methods that aren't there in the first place.
ok thanks, I realized I call the right method when I tested in console and a wrong one in my code editor.
-1

Your error message complains about the filter method not being available on a NodeType In your example you specified a NodeType Array.

Try this:

<NodeType>list

It's still not an array though.

2 Comments

list must be an array for filter method.
but thanks, It makes me realize I call the right method when I tested in console and a wrong one in my code editor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.