Search code examples
typescriptstring-literals

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

Solution

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