【问题标题】:Can't get babel to compile string literal type with interpolation on typescript无法让 babel 在打字稿上使用插值来编译字符串文字类型
【发布时间】: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&lt;`theader_${N}`&gt; 怎么样?
  • @kaya3,感谢您的评论。我得到一个“模板文字类型不能有任何替换”
  • 在这种情况下,也许像 Concat&lt;A extends string, B extends string&gt; = `${A}${B}`;type HeaderClassName&lt;N extends string&gt; = Concat&lt;'theader_', Lowercase&lt;N&gt;&gt;; 这样的辅助类型会起作用?
  • 它没有,没有插值工作:/
  • 您确定您使用的是支持此功能的最新版本的 Babel 吗?

标签: reactjs typescript babeljs


【解决方案1】:

经过大量挖掘,我发现正在使用的 babel 版本是 react-app-rewired 和 react-scripts 包中的那个。几个小时后,你的脑袋就不再工作了。

我更新了它们,一切正常。

感谢所有花一分钟时间提供帮助的人。

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 2022-07-21
    • 2018-04-28
    • 2019-01-19
    • 2019-02-22
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 2016-11-11
    相关资源
    最近更新 更多