Within the TypeScript function declaration provided below, the parameter type alignment
consists of unioned literals.
function printText(s: string, alignment: "left" | "right" | "center") {
// ...
}
As per the documentation on literals, a variable of type string
cannot be assigned to alignment
directly because it strictly needs to match one of "left"
, "right"
, or "center"
.
The docs suggest using a type assertion, for example:
printText("Test", printerConfig.textAlignment as "left");
An alternative approach could be:
const printerConfig = { textAlignment: "left" } as const;
printText("Test", printerConfig.textAlignment);
Now consider this scenario:
- The
printText
function is part of a library and its source code cannot be modified. - I receive a
printerConfig
object as input or need to extract it from a JSON configuration file. - The
textAlignment
property inprinterConfig
is of typestring
.
How would I go about invoking the printText
function?