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

user504909 picture user504909 · May 2, 2019 · Viewed 11.9k times · Source

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?

Answer

Adrian Brand picture Adrian Brand · May 2, 2019

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.