Howard
Howard

Reputation: 4604

[Typescript]: How to use namespaced value in type?

I have following module:

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;
}

This is not working, and i got error:

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

Am i wrong about the usage? Typescript version i used is: 2.1.5

Upvotes: 1

Views: 85

Answers (2)

Aluan Haddad
Aluan Haddad

Reputation: 31803

If you want to use them directly as types and as values then the following will work cleanly

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;
}

Upvotes: 2

Misaz
Misaz

Reputation: 3985

Because Const is not a Type and you canot use const as type. You can exchange const for type if it does not broke another part of your app.

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

Upvotes: 1

Related Questions