Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading