【发布时间】:2019-03-20 16:09:38
【问题描述】:
我正在使用 TypeScript 来开发我的应用程序。我正在尝试创建一个接口(或类型),它是几个常量之一或随机字符串。
描述我正在尝试构建的伪代码:
contants.ts:
export const ERROR_A = "Error A";
export const ERROR_B = "Error B";
export const ERROR_C = "Error C";
types.ts:
type SWITCH_ERROR = ERROR_A | ERROR_B | ERROR_C | string
我知道这样每个字符串都可能是错误的。我之所以要这样做,是为了可以轻松维护代码库,并且每个已知错误都有它的类型。稍后将在 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.
}
}
问题是我尝试这样做:
import { ERROR_A } from "./some/Path";
export type SwitchError = ERROR_A;
但这会引发错误:
[ts] Cannot find name 'ERROR_A'.
我做错了什么?如何在 TypeScript 中设计这样的东西?或者这是糟糕的设计?如果是的话,我还能怎么做?
【问题讨论】:
标签: typescript typescript-typings typescript-types