4

I am creating an interface in which I need a property to be explicitly set to a value when it's used.

I have seen I can specify multiple possible values for a property

e.g.

propertyA: 'x' | 'y' | 'z';

Would this work for single value?

So if I did something like:

propertyA: 'x'

When the interface gets used to define an object somewhere else, would the compiler complain if a different value was attempted to be used.

Is there a way in my example above, I can say this property can only ever hold a value of 'x'?

I came across type's and wondered if this could be a better way for me to achieve this rather than an interface.

Please correct me if I have misunderstood something here.

mindparse
  • 6,115
  • 27
  • 90
  • 191
  • Do this match your [requirement](https://stackoverflow.com/questions/26471239/typescript-constants-in-an-interface)? – leopal Feb 07 '19 at 12:03

2 Answers2

3

propertyA: 'x' | 'y' | 'z'; uses two typescript advanced type features.

Union types which give us the ability to create a new type that can be either one of a given set of types. So number | string means something is either number or string

String literal types are types that only accept a single value. So 'z' can be used as a type, with the meaning that something will only ever be that value. Given this you can write:

interface Foo {
    x: 'x'
}
let foo: Foo = {
    x: 'x' //ok
}

let bar: Foo = {
    x: 'y' //err
}

So yes you can have an interface with a member that is only ever one value. This is usually useful in conjunction with discriminated unions.

Trupti J
  • 512
  • 1
  • 4
  • 16
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
0

You cannot assign a value to an interface's param. You can only do it in class or module.

Nguyen Phong Thien
  • 3,237
  • 1
  • 15
  • 36