首页 > 解决方案 > 模板文字作为 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

解决方案


当函数被调用时,TypeScript 会自动扩展表达式的类型

`Hi ${value}`

string.

您可以通过使用来修复它as const以防止扩大:

randomFunction(`Hi ${value}` as const)

推荐阅读