FrancoSF
FrancoSF

Reputation: 561

Creating String Literal Type with const

I'm trying to define a new type as String Literal using a set of const. Apparently TypeScript doesn't to like the idea. What am I doing wrong? Here a simple case to recreate the error.

module Colors {

    export const Red = '#F00';
    export const Green = '#0F0';
    export const Blue = '#00F';

    export type RGB = Colors.Red | Colors.Green | Colors.Blue; // Error!
}

var c: Colors.RGB = Colors.Green;

The error message is

Module 'Colors' has no exported member 'Red'.

Upvotes: 2

Views: 855

Answers (2)

FrancoSF
FrancoSF

Reputation: 561

This could be a reasonable compromise:

module Colors {

    export type RGB = '#F00' | '#0F0' | '#00F';

    export const Red: RGB = '#F00';
    export const Green: RGB = '#0F0';
    export const Blue: RGB = '#00F';

}

In this way I can use one of those consts every time a Colors.RGB type is expected. The following code is now valid:

function foo( color: Colors.RGB) {
    //...
}

foo(Colors.Red);

Upvotes: 1

basarat
basarat

Reputation: 275927

new type as String Literal using a set of const

You cannot use a const as a type annotation. They are in different declaration spaces https://basarat.gitbooks.io/typescript/content/docs/project/declarationspaces.html

Fix

module Colors {

    export const Red = '#F00';
    export const Green = '#0F0';
    export const Blue = '#00F';

    export type RGB = '#F00' | '#0F0' | '#00F';
}

Upvotes: 2

Related Questions