Ben Aston Ben Aston - 17 days ago 12
TypeScript Question

Conditionally adding a property in TypeScript

I'd like to conditionally add a property to an object (or maybe I mean a class - I am unsure of the actual semantics in TypeScript).

import IMetadata from './metadata-interface';

export default class MetaData {

[idx: string]: IMetadata;

public 'foo' = {
name: 'foo',
} as IMetadata;

public 'bar' = {
name: 'bar',
} as IMetadata;
};


But how do I conditionally add bar to the object? Can I do something like:

export default class MetaData {

[idx: string]: IMetadata;

public 'foo' = {
name: 'foo',
} as IMetadata;

if(condition) {
public 'bar' = {
name: 'bar',
} as IMetadata;
}
};

Answer

Use an if statement:

export default class MetaData {

    [idx: string]: IMetadata;

    public 'foo' = {
        name: 'foo',
    } as IMetadata;

    public 'bar'?: IMetadata;

    constructor(condition: boolean) {
        if (condition) {
            this.bar = {
                name: 'bar',
            };
        }
    }
}
Comments