【问题标题】:Define type by string按字符串定义类型
【发布时间】:2022-01-11 00:30:16
【问题描述】:

我在一些外部资源(我想在我的项目中使用)中看到了以下评估:

const INIT: 'jsonforms/INIT' = 'jsonforms/INIT'
  1. 通过字符串INIT: 'jsonforms/INIT' 定义类型是什么意思?字符串('jsonforms/INIT')怎么可能是类型?

    这官方叫什么?

  2. 我的 Webpack 在构建过程中抱怨这个问题,需要一个额外的加载器:

    styleTagTransform.js:16 Uncaught Error: Module parse failed: Unexpected token (36:17)
    File was processed with these loaders:
     * ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
     * ./node_modules/source-map-loader/dist/cjs.js
    You may need an additional loader to handle the result of these loaders.
    | import { ErrorTranslator, Translator } from '../i18n';
    | 
    > export const INIT: 'jsonforms/INIT' = 'jsonforms/INIT';
    | export const UPDATE_CORE: 'jsonforms/UPDATE_CORE' = `jsonforms/UPDATE_CORE`;
    | export const SET_AJV: 'jsonforms/SET_AJV' = 'jsonforms/SET_AJV';
    

这里有另一个投诉:

export type CoreActions =
  | InitAction
  | UpdateCoreAction
  | UpdateAction;

上面的语法是什么意思?

Uncaught Error: Module parse failed: Unexpected token (65:7)
File was processed with these loaders:
 * ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
 * ./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
| export const REMOVE_DEFAULT_DATA = `jsonforms/REMOVE_DEFAULT_DATA`;
| 
> export type CoreActions =
|   | InitAction
|   | UpdateCoreAction

【问题讨论】:

  • typescriptlang.org/docs/handbook/2/…(注意const INIT = 'jsonforms/INIT' 已经被推断为const INIT: "jsonforms/INIT",因为它是const)。
  • 'jsonforms/INIT' 它是一个类型,因为它是一个常数,这意味着即使您没有明确提供 'jsonforms/INIT' 的类型,您也不能向该变量添加除 'jsonforms/INIT' 之外的任何字符串一个类型,但在 let 的情况下,您必须明确添加类型 'jsonforms/INIT' 以防止任何其他字符串值

标签: typescript webpack


【解决方案1】:

我想缺少的附加加载器是ts-loader

字符串('jsonforms/INIT')如何成为类型?

在 TypeScript 中,此类型是 literal

export type CoreActions =
| InitAction
| UpdateCoreAction
| UpdateAction;

上面的语法是什么意思?!

这个是union

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 2020-03-17
    • 2013-11-27
    • 2020-08-23
    • 2021-08-20
    • 1970-01-01
    • 2021-08-10
    相关资源
    最近更新 更多