【问题标题】:How do I call a method taking a union of string literals when I have a normal string?当我有一个普通字符串时,如何调用一个采用字符串文字并集的方法?
【发布时间】:2022-11-25 00:11:05
【问题描述】:

在以下 TypeScript 函数声明中,alignment 参数类型是一组联合文字。

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

根据docs on literalsstring类型的变量不能分配给alignment,因为严格来说它不是"left" | "right" | "center"类型。

文档说要使用这样的类型断言:

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

这也行得通:

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

printText("Test", printerConfig.textAlignment);

现在想象一下:

  1. printText 函数在库中,我无法更改它。
  2. 我的代码已传递一个 printerConfig 对象,或者它会从 JSON 配置文件中读取它。
  3. textAlignment 属性的类型为string

    如何调用printText函数?

【问题讨论】:

  • 提示:你会如何在 JavaScript 中做到这一点?解决方案在 TypeScript 中基本相同。

标签: typescript


【解决方案1】:

我认为如果 alignment 不是一个合理的值,您将不想调用 printText - 如果您的代码的调用者传递了一个错误的配置对象,或者 JSON 格式错误怎么办?您可能希望在调用 printText 之前抛出一个错误。

在传递之前缩小 textAlignment 的类型。如果类型不正确,则抛出错误。

// 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);

【讨论】:

  • 这就是我的想法。这很有趣,因为将您的方法设计为采用联合有效地将责任转嫁给调用者以编写检查代码。根据他们的观点,这可能会被该功能的消费者视为烦人的额外麻烦。
  • 是的,应该是这样。如果您设计了一个函数,则函数的调用者可以按照您设定的规则调用它。如果你的函数被传递了它无法理解的值(考虑到它的明确规则),只有调用者才能知道在这种情况下该怎么做。
猜你喜欢
  • 1970-01-01
  • 2021-07-10
  • 2021-01-25
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
  • 2022-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多