typescript - 模板文字作为 Typescript 中的函数参数
问题描述
给出下面的例子:
type AllNames = 'andre' | 'willian' | 'pedro'
type HiNames = `Hi ${AllNames}`
const value: AllNames = 'andre'
const randomFunction = (prop: HiNames) => `${prop}, how are you?`
randomFunction(`Hi ${value}`)
VSCode 抛出以下错误:
Argument of type 'string' is not assignable to parameter of type '"Hi andre" | "Hi willian" | "Hi pedro"'.
不会Hi ${value}
总是评估为Hi andre
?
如何在 Typescript 中使用模板文字作为函数参数?非常感谢任何帮助。谢谢。
解决方案
当函数被调用时,TypeScript 会自动扩展表达式的类型
`Hi ${value}`
到string
.
您可以通过使用来修复它as const
以防止扩大:
randomFunction(`Hi ${value}` as const)
推荐阅读
- django - 从 one_to_one 关系中检索已回答的(非空/空)问题
- c++ - 在 Omnet++ 上使用 INet 更改消息内容
- haskell - 如何为具有幻像类型变量的新类型定义 MonadUnliftIO 实例?
- wordpress - woocommerce 在我的订单页面中显示不正确的订单
- autodesk-forge - 如何获取对象的坐标
- excel - 将 Excel 公式执行到另一个工作表中
- javascript - 如何在 json 对象内的特定键值上应用函数
- jquery - AngularJS 将 json 数据以列表的形式传递给 mvc 控制器
- python - 如何仅使用 Jupyter Notebook 安装 Qiskit?
- php - 传递的函数 0 的参数太少,而 DI 容器恰好期望 1