can I use String literal types for syntactic sugar?

Viewed 38

I can use the literal types to give the user some suggestions but without depriving him of using custom strings, i try this :

type  fooType = string | 'suggestions-1' | 'suggestions-2';

I also tried using the String class and so it seems to work but not good for my purpose

type fooType = String | 'suggestions-1' | 'suggestions-2';

i reproduce all in this TypeScript playground

2 Answers
type StringAndOthers<T> = T | (string & Record<never, never>);
type FooType = StringAndOthers<"suggestions-1" | "suggestions-2">;

const suggestion: FooType = 'suggestions-1';
const suggestion1: FooType = 'suggestions-2';
const suggestion3: FooType = 'suggestions-4';

I think a better approach would be to declare an enum first

export enum abc {
    a = 'A',
    b = 'B'
   }

and then declare your type:

a:abc|string 

and while assigning maybe use values from abc instead of typing strings

Related