Home > Software design >  Type 'undefined' is not assignable to type 'string' when destructing an object
Type 'undefined' is not assignable to type 'string' when destructing an object

Time:02-05

I'm destructing an object as following:

const { lang, ...params } = ctx.query;

But TS gives me an error in this line:

if (!value.includes(params[key])) return false;

enter image description here

How can I solve this issue?

CodePudding user response:

Use .includes(params[key] as string) (or .includes(<string>params[key])) to tell Typescript you know it's a string.

CodePudding user response:

first check if params[key] is defined if (params && params[key]) {...

CodePudding user response:

Typescript is understanding your property represented by params[key] has either a type of an array, or a string, the property is even undefined because maybe key does not exist in your object.

You could first check if the property exists Then you could check if the type of your property is a string this way

if (params[key] && typeof params[key] === string && !value.includes(params[key])) return false;

Ideally you would have a parent if block like this

if(params[key] && typeof params[key] === string){
   //The property exists and if of type string, do your thing with it.
   if (!value.includes(params[key])) return false;
}else{
   //Why it's not the type you expected?
   //Do something, log or throw an error for example
}

This way Typescript knows it will only reach the child if when the params[key] property is really a string, and then the typescript checker/compiler will not complain about that uncertainty.

  •  Tags:  
  • Related