mindparse
mindparse

Reputation: 7225

Can you specify a property must hold a certain value in an interface?

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.

Upvotes: 4

Views: 1217

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249616

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.

Upvotes: 3

Nguyen Phong Thien
Nguyen Phong Thien

Reputation: 3387

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

Upvotes: 0

Related Questions