2

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'.

2 Answers 2

2

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';
}
Sign up to request clarification or add additional context in comments.

4 Comments

Seems there is no way to reduce the duplication. One could type the constants to get some measure of typo-checking: export const Red: RGB = '#F00'
yup ¯\_(ツ)_/¯ 🌹
It's only a little more safety, though, does not prevent export const Red: RGB = '#0F0' // is actually green
Thank you @Thilo , I read your note only after posting my answer.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.