我正在使用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 中设计这样的东西?还是这个糟糕的设计?如果是,我还能怎么做?
错误是因为您只将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;
Hayden Hall 建议使用枚举也很好,因为枚举成员会自动定义为名称和类型。 但是你可以避免所有这些,只写type SWITCH_ERROR = string
;当ERROR_A
、ERROR_B
和ERROR_C
是特定的字符串时,它等效于type SWITCH_ERROR = ERROR_A | ERROR_B | ERROR_C | string
。
如下所示的内容应该可以解决问题(假设您的错误是一个字符串(:
enum Errors {
ERROR_A = 'Error A',
ERROR_B = 'Error B',
ERROR_C = 'Error C',
}
function handleError(error: string) : void {
switch(error) {
case Errors.ERROR_A:
// Handle ERROR_A
case Errors.ERROR_B:
// Handle ERROR_B
case Errors.ERROR_C:
// Handle ERROR_C
default:
// Handle all other errors...
}
}