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?
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.
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.
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.
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.
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.
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