[Typescript]:如何在类型中使用命名空间值?

时间:2017-01-28 03:33:30

标签: typescript

我有以下模块:

a.ts

export namespace METHODS {

    export const GET = 'get';

    export const POST = 'post';

    export const PUT = 'put';

    export const DELETE = 'delete';

}

b.ts

import { METHODS } from './a.ts';

export interface Route {
    method: METHODS.GET | METHODS.POST;
}

这不起作用,我收到了错误:

Namespace '"a".METHODS' has no exported member 'GET'

我的用法错了吗?我使用的Typescript版本是:2.1.5

2 个答案:

答案 0 :(得分:2)

如果您想直接将它们用作类型和值,那么以下内容将干净利落

export namespace METHODS {

  export const GET = 'get';

  export type GET = typeof GET;

  export const POST = 'post';

  export type POST = typeof POST;

  export const PUT = 'put';

  export type PUT = typeof PUT;

  export const DELETE = 'delete';

  export type DELETE = typeof DELETE;
}

答案 1 :(得分:1)

因为Const不是Type,所以你可以使用const作为类型。如果没有破坏应用程序的其他部分,您可以将const替换为类型。

export namespace METHODS {
  //export const GET = 'get';
    export type GET = 'get';
    export type POST = 'post';
    export type PUT = 'put';
    export type DELETE = 'delete';
}