Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Type 'string | string[]' is not assignable to type 'string'

I am using node + typescript and integrated swagger for API Calls. I have a following request in swagger

http://localhost:3033/employees/search/?username=test

Here I want to find the records having username = test.

So I parse the query string using URL module, like below and I am getting the username in my console.

var params = URL.parse(req.url, true).query;
console.log(params); //gives me [Object: null prototype] { username: 'test' } in my console

But whenever I try to assign params.username to a constant like below

const username:string =params.username;

It gives me the following error

Type 'string | string[]' is not assignable to type 'string'. Type 'string[]' is not assignable to type 'string'.

My full code is as below

import * as URL from 'url';

public getUserByName = async (req: Request, res: Response, next: NextFunction) => {
var params = URL.parse(req.url, true).query;
const username:string =params.username;

try {
  const findOneUserData: Employee = await this.userService.findUserByName(username);
  res.status(200).json({ data: findOneUserData, message: 'findOne' });
} catch (error) {
  next(error);
}

}

like image 643
Oops Avatar asked Feb 07 '20 09:02

Oops


People also ask

How do I fix undefined string is not assignable to type string?

The "Type 'string | undefined' is not assignable to type string" error occurs when a possibly undefined value is assigned to something that expects a string . To solve the error, use the non-null assertion operator or a type guard to verify the value is a string before the assignment.

Is not assignable to type string enum?

The error "Type string is not assignable to type Enum" occurs when we try to use a string literal in the place of an enum value. To solve the error, use dot or bracket notation to access the specific enum property or use a type assertion.

How do you assign a string undefined to a string?

The typescript compiler performs strict null checks, which means you can't pass a string | undefined variable into a method that expects a string . To fix this you have to perform an explicit check for undefined before calling luminaireReplaceLuminaire() .

Can I assign a string type to a number type?

Property 'name' of type 'string' is not assignable to 'string' index type 'number'. Property 'name' of type 'string' is not assignable to 'string' index type 'number'. However, properties of different types are acceptable if the index signature is a union of the property types:

Which argument is not assignable to parameter of type [number]?

Argument of type 'readonly [3, 4]' is not assignable to parameter of type ' [number, number]'. The type 'readonly [3, 4]' is 'readonly' and cannot be assigned to the mutable type ' [number, number]'.

Why cannot assign to 0 in typescript?

Cannot assign to '0' because it is a read-only property. Cannot assign to '0' because it is a read-only property. Tuples tend to be created and left un-modified in most code, so annotating types as readonly tuples when possible is a good default.

What is the difference between string[] and stringnumberpair?

The type 'readonly string []' is 'readonly' and cannot be assigned to the mutable type 'string []'. A tuple type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions. Here, StringNumberPair is a tuple type of string and number .


3 Answers

You can tell the compiler to cast the param as a string with

const username = params.username as string
like image 168
louis_guitton Avatar answered Oct 16 '22 16:10

louis_guitton


The problem in your code is, that params.username can be either a string or a string[].

The following scenario returns a simple string

const {query} = url.parse('example.com?test=1', true);
// query.test === '1'

while the example below returns an array because the same query-parameter key is used twice

const {query} = url.parse('example.com?test=1&test=2', true);
//query.test === ['1', '2']

So you could handle the array case explicitly e.g.

const username = Array.isArray(params.username) ? params.username[0] : params.username
like image 40
Klaus Bayrhammer Avatar answered Oct 16 '22 16:10

Klaus Bayrhammer


Okay ,so I got the mistake that I made. The first one was what @ford04 has mentioned in the comment. I was directly assigning Object to the string. I changed it in my question. The second was converted the parsed query-string to string by toString() function.

public getUserByName = async(req: Request, res: Response, next: NextFunction) => {
  var params = URL.parse(req.url, true).query;
  console.log(params.username);
  const username: string = params.username.toString(); //this is the key

  try {
    const findOneUserData: Employee = await this.userService.findUserByName(username);
    res.status(200).json({
      data: findOneUserData,
      message: 'findOne'
    });
  } catch (error) {
    next(error);
  }
}
like image 21
Oops Avatar answered Oct 16 '22 18:10

Oops