Home > Mobile >  Type 'RegExpExecArray | null' must have a '[Symbol.iterator]()' method that retu
Type 'RegExpExecArray | null' must have a '[Symbol.iterator]()' method that retu

Time:09-10

I'm relatively new to TypeScript. Know the basics but encountered a typecast error that I haven't found a solution to.

const [full, id]: string | null = /.*media\/[^\/] \/(.*)/.exec(item.uri)

typescript throws error on: [full, id]

Type 'RegExpExecArray | null' is not assignable to type 'string | null'.
Type 'RegExpExecArray' is not assignable to type 'string'.ts(2322)
Type 'string | null' must have a '[Symbol.iterator]()' method that returns an iterator.

typecast Any ofc works but wanna do this properly, but haven't found what exactly TS wants me to do, while trying to search for an answer... So turn here now in hope for guidance.

Thanks!

CodePudding user response:

Use the type that TypeScript suggests:

const a: RegExpExecArray | null = /.*media\/[^\/] \/(.*)/.exec(item.uri)

console.log(a)

CodePudding user response:

Ok, found a solution to the issue:

const id: RegExpExecArray | null = /.*media\/[^\/] \/(.*)/.exec(item.uri)
return id?.[1]?.replace(/:/g, '_')

This code properly type cast but also do the check "object is possible 'null'" TS error message.

Thanks for everyones input. Learned a lot.

  • Related