2

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

amir yeganeh
  • 647
  • 3
  • 11
  • 23

2 Answers2

1

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.

qqilihq
  • 10,794
  • 7
  • 48
  • 89
-2

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);
robdev91
  • 1,006
  • 1
  • 10
  • 18
  • I did what you said, problem with substr looks to be fixed but now I get this error on ip `Type 'string | string[] | undefined' is not assignable to type 'String'. Type 'undefined' is not assignable to type 'String'.ts(2322)` – amir yeganeh Dec 02 '20 at 10:34