Property 'substr' does not exist on type 'string | string[]'

Viewed 1586

i had a code in javascript and I'm trying to convert it to typescript

          var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
          if (ip.substr(0, 7) == "::ffff:") {
            ip = ip.substr(7);

this is a piece of my code which used to work correctly in js but now I get this error for substr

Property 'substr' does not exist on type 'string | string[]'. Property 'substr' does not exist on type 'string[]'.ts(2339)

I assume I should add type for ip variable but I don't know what type should exactly be assigned to it.

any help would be appreciated

2 Answers

There’s a reason why the property is defined as string | string[] (and this is why you use TypeScript in the first place). Probably, there are several values for a header key, so simply “assuming” it to be always a string is wrong!

Simplest solution -- do a type check before you try to invoke .substr as follows:

if (typeof ip === 'string' && ip.substr(0, 7) == "::ffff:") {
  // …

Better would be, to also handle the case that it actually is an array. But the logic depends on your specific requirements.

Use String instead of string refer here

So, your code will be

          var ip: String = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
          if (ip.substr(0, 7) == "::ffff:") {
            ip = ip.substr(7);
Related