Adam Baranyai
Adam Baranyai

Reputation: 3867

Default string type values in typescript

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?

Upvotes: 0

Views: 144

Answers (2)

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

Upvotes: 0

kabanus
kabanus

Reputation: 25980

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.

Upvotes: 2

Related Questions