2

I failed to find information on this elsewhere. I want to create a type that has both defined strings or allows any type of string to be used, but giving auto suggestion for the defined entries.

Right now if I add the // | string at the end, it sort of takes over, and doesn't give any auto suggestion.

                                      // if I add this it stops suggestions
type DefinedLetters = 'A' | 'B' | 'C' // | string

const Letter: DefinedLetters  = '' // Should suggest A, B or C, but also allow D, E, F, etc.

2 Answers 2

6

I found this cool LiteralUnion type researching this for you, I think it works like a charm!

type LiteralUnion<T extends U, U = string> = T | (U & { });
type DefinedLetters = LiteralUnion<'A' | 'B' | 'C'>

const Letter: DefinedLetters  = "Cool!"
Sign up to request clarification or add additional context in comments.

2 Comments

Neat! Seems that if you want you can get the same effect like: type DefinedLetters = 'A' | 'B' | 'C' | (string & { });
@NicholasTower Indeed, that works too, the LiteralUnion just encapsulates that last string bit for re-use
1

Why not create an enum and then in your usage, you can just specify your type as

let letter2: DefinedLetters | string;

Example

enum DefinedLetters {
    A = 'A',
    B = 'B',
    C = 'C'
}

let letter1: DefinedLetters;
letter1 = DefinedLetters.A; // <- ok
letter1 = 'test'; // <-- ts error

let letter2: DefinedLetters | string;
letter2 = DefinedLetters.A; // <- ok
letter2 = 'test'; // <- ok

Not quite a type approach, but you get the same thing in this example.

1 Comment

Thanks for the effort, but Nick's answer is more in line of what I want right now.

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.