Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescripts type 'string | string[]' is not assignable to type 'string', what is the 'string | string[]' type? how to cast them to string?

When I do TypeScript:

let token = req.headers['x-access-token'] || req.headers['authorization'] as string;

I have fellow error:

Argument of type 'string | string[]' is not assignable to parameter of type 'string'

Any one know what is 'string | string[]' type? I mean if I want use logical 'or' of two string in typescript. How to do it?

And How to cast 'string | string[]' type to string type?

like image 747
user504909 Avatar asked May 02 '19 05:05

user504909


People also ask

How do I fix type string undefined 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.

How do you assign a string undefined to a string in TypeScript?

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() . Save this answer.

Is not assignable to parameter of type string?

The error "Argument of type string | undefined is not assignable to parameter of type string" occurs when a possibly undefined value is passed to a function that expects a string . To solve the error, use a type guard to verify the value is a string before passing it to the function.

What is String [] in TypeScript?

In TypeScript, the string is sequence of char values and also considered as an object. It is a type of primitive data type that is used to store text data. The string values are used between single quotation marks or double quotation marks, and also array of characters works same as a string.


1 Answers

Try

let token = (req.headers['x-access-token'] || req.headers['authorization']) as string;

The compiler thinks req.headers['some string'] is an array of string, when you cast one side of the or operator you get a type of string or array of string. So do the or on both of them and then coerce the result to be a string.

like image 124
Adrian Brand Avatar answered Sep 21 '22 06:09

Adrian Brand