0

Consider the following code:

type PredefinedStrings = 'test' | 'otherTest';

interface MyObject {
    type: string | PredefinedStrings;
}

The MyObject interface should have a single type property, which could be either one of the PredefinedStrings or a string that was defined somewhere along the line by the developer.

What I would like to achieve with this, is to let the developer type in any string as the type property (this is achieved by the above code), BUT also show the predefined types as an IntelliSense suggestion when starting to provide the value for the type property.

Is there any way to achieve both of the above requirements?

2 Answers 2

2

Why not use a string enum, which seems to be the builtin to do what you want:

enum Tests {
    Test = 'test',
    OtherTest = 'otherTest'
}

This should allow Intellisense to autocomplete the enum values.

Sign up to request clarification or add additional context in comments.

Comments

0

Some addition to @kabanus answer:

Also, to achieve completely what you want, you can define MyObject as generic:

interface MyObject<T extends string> {
  type: T | PredefinedStrings;
}

After that consumer of your interface will be able to define its own type like this:

enum SomeEnum {
  TYPE1 = "TYPE1",
  TYPE2 = "TYPE2",
}

type ExtendedMyObject = MyObject<SomeEnum>;

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.