as never
is very occasionally needed in TypeScript. Let's look at an example where it's necessary.
Let's imagine we want to format some input based on its
typeof
. We first create a
formatters
object that maps
typeof
to a formatting function:
const formatters = {
string : (input : string) => input .toUpperCase (),
number : (input : number) => input .toFixed (2),
boolean : (input : boolean) => (input ? "true" : "false"),
Next, we create a format
function that takes an input of string | number | boolean
and formats it based on its typeof
.
const format = (input : string | number | boolean) => {
// We need to cast here because TypeScript isn't quite smart
// enough to know that `typeof input` can only be
// 'string' | 'number' | 'boolean'
const inputType = typeof input as
| "string"
| "number"
| "boolean";
const formatter = formatters [inputType ];
return formatter (input );Argument of type 'string | number | boolean' is not assignable to parameter of type 'never'.
Type 'string' is not assignable to type 'never'.2345Argument of type 'string | number | boolean' is not assignable to parameter of type 'never'.
Type 'string' is not assignable to type 'never'.};
But there's a strange error:
Type 'string' is not assignable to type 'never'.
What's going on here?
Unions Of Functions With Incompatible Params
Let's take a deeper look at the type of formatter
inside our format
function:
const format = (input : string | number | boolean) => {
const inputType = typeof input as
| "string"
| "number"
| "boolean";
const formatter = formatters [inputType ];