【发布时间】:2021-06-26 18:18:48
【问题描述】:
我有一个使用打字稿的反应应用程序,我需要使用带有插值的文字字符串类型创建类型:
class ExampleClass {
product_id!: number;
product_name!: string;
}
export type HeaderClassNames<N extends string> = `theader_${Lowercase<N>}`;
type HeaderClasses = HeaderClassNames<keyof ExampleClass>;
“HeaderClasses”产生:
type HeaderClasses = "theader_product_id" | "theader_product_name"
tsc 可以正常工作,但是当 babel 转译时,它无法识别模板:
Unexpected token (8:72)
6 |
7 | export type TableHeaderConfig<Keys extends string> = Record<Keys, TableHeaderColumn>;
> 8 | export type HeaderClassNames<N extends string> = `theader_${Lowercase<N>}`;
| ^
9 | export type ColumnClassNames<N extends string> = `column_${Lowercase<N>}`;
10 |
Babel said 它开始支持此功能,但我安装并重新安装 babel/core,甚至手动尝试了 babel/parser(提交的位置),但没有任何变化。
感谢您的帮助。
【问题讨论】:
-
Lowercase<`theader_${N}`>怎么样? -
@kaya3,感谢您的评论。我得到一个“模板文字类型不能有任何替换”
-
在这种情况下,也许像
Concat<A extends string, B extends string> = `${A}${B}`;和type HeaderClassName<N extends string> = Concat<'theader_', Lowercase<N>>;这样的辅助类型会起作用? -
它没有,没有插值工作:/
-
您确定您使用的是支持此功能的最新版本的 Babel 吗?
标签: reactjs typescript babeljs