TypeScript:常量或字符串之一的接口或类型

J. *_*ers 5 typescript typescript-typings typescript-types

我正在使用 TypeScript 来开发我的应用程序。我正在尝试创建一个接口(或类型),它是几个常量之一或随机字符串。

伪代码来描述我正在尝试构建的内容:

contants.ts

export const ERROR_A = "Error A";
export const ERROR_B = "Error B";
export const ERROR_C = "Error C";
Run Code Online (Sandbox Code Playgroud)

types.ts

type SWITCH_ERROR = ERROR_A | ERROR_B | ERROR_C | string
Run Code Online (Sandbox Code Playgroud)

我知道这样每个字符串都可能是错误的。我想这样做的原因是,代码库可以轻松维护,并且每个已知错误都有其类型。该错误稍后将在如下 switch 语句中处理:

switchExample.ts

export const someFunc(error: SwitchError): void => {
  switch(error) {
    case ERROR_A:
      // Do something
    // ... continue for each error.
    default:
      // Here the plain string should be handled.
  }
}
Run Code Online (Sandbox Code Playgroud)

问题是我尝试这样做:

import { ERROR_A } from "./some/Path";

export type SwitchError = ERROR_A;
Run Code Online (Sandbox Code Playgroud)

但这会引发错误:

[ts] Cannot find name 'ERROR_A'.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?如何在 TypeScript 中设计这样的东西?或者这是一个糟糕的设计?如果是的话,我还能怎么做?

Mat*_*hen 8

错误是因为您只定义ERROR_A了一个值,但您试图将其用作类型。(错误消息没有帮助;我最近提交了一个问题来改进它。)要将每个名称定义为值和类型,您可以在 中使用以下内容constants.ts

export const ERROR_A = "Error A";
export type ERROR_A = typeof ERROR_A;
export const ERROR_B = "Error B";
export type ERROR_B = typeof ERROR_B;
export const ERROR_C = "Error C";
export type ERROR_C = typeof ERROR_C;
Run Code Online (Sandbox Code Playgroud)

Hayden Hall 建议使用枚举也很好,因为枚举成员自动定义为名称和类型。但是你可以避免这一切,只写type SWITCH_ERROR = string; 它相当于type SWITCH_ERROR = ERROR_A | ERROR_B | ERROR_C | stringERROR_AERROR_B以及ERROR_C特定字符串。