How do I call a method taking a union of string literals when I have a normal string?

In the following TypeScript function declaration, the alignment parameter type is a set of unioned literals.

function printText(s: string, alignment: "left" | "right" | "center") {
  // ...

According to the docs on literals, a variable of type string is not assignable to alignment because strictly speaking it’s not of type "left" | "right" | "center".

The documentation says to use a type assertion like so:

printText("Test", printerConfig.textAlignment as "left");

And this would also work:

const printerConfig = { textAlignment: "left" } as const;

printText("Test", printerConfig.textAlignment);

Now imagine:

  1. The printText function was in a library and I could not change it.
  2. My code had been passed a printerConfig object or it’d read it from a JSON config file.
  3. That its textAlignment property was of type string.

How can I call the printText function?

>Solution :

I’d think you would not want to call printText if the alignment was not a sensible value – what if the caller of your code passed a bad config object, or the JSON was badly formatted? You’d probably want to throw an error before calling printText.

Narrow the type of the textAlignment before passing it. If it’s not the right type, throw an error.

// have checks of textAlignment narrow this new variable
const { textAlignment } = printerConfig;
if (textAlignment !== 'left' && textAlignment !== 'right' && textAlignment !== 'center') {
  throw new Error(`Invalid textAlignment: ${textAlignment}`);
printText("Test", textAlignment);

Leave a Reply