user8401765
user8401765

Reputation:

how to create a class with a variable that could have one of two types angular

I want to create a class to define a type of data. I want to restrict the data types of the fields in it. But the problem is that I want the 'value field to have one of two types depending on a particular configuration.

I will make multiple object of this class, and some of them have value as a string and others as an object.

export class Raw {
    'enabled': boolean;
    'value': -------> string/object <-------;
    'data': object;
}

Upvotes: 3

Views: 1365

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97227

Use a union type:

export class Raw {
    value: string | object;
}

Note: there's no need to 'quote' your property names unless they are otherwise invalid identifiers (e.g. they contain spaces).

Upvotes: 7

Related Questions