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 🙏🏻
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With