0

Is it possible to define a variable with the type string and then define which possible values that string can have?

colorScheme?: string = 'positive|negative'; //must be a string 
                                             and must have the value "positive" or "negative"

Thank you.

UPDATE It does not appear to work when defined in a component:

type ColorScheme = 'positive' | 'negative';

export class MyButtonComponent {
      @Input() colorScheme?: ColorScheme;

Now it is correct. Thank you.

11
  • 3
    colorScheme?: 'positive' | 'negative = ...' Commented Jul 5, 2022 at 15:29
  • why the =..."? Can you clarify me? Thank you. Commented Jul 6, 2022 at 17:14
  • that's where you put whatever value you want to assign initially Commented Jul 6, 2022 at 17:16
  • Can you write what to write? colorScheme?: 'positive' | 'negative = positive' ? Thank you. Commented Jul 6, 2022 at 17:45
  • 1
    yes, exactly: colorScheme?: 'positive' | 'negative' = "positive" Commented Jul 6, 2022 at 17:46

1 Answer 1

1

Yes, it's called a union type !

type ColorScheme = 'positive' | 'negative';

const scheme1: ColorScheme = 'negative'; // ok
const scheme2: ColorScheme = 'positive'; // ok 
const scheme3: ColorScheme = 'foobar'; // ko

Playground

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

1 Comment

Sorry, i misunderstood here to place the type. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.