2

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;
    }
};
5
  • "or maybe I mean a class". What's your goal here? Class and object are the same concepts like in other class-based languages. Do you really want to have conditional logic in constructing a class definition? Commented Nov 17, 2016 at 20:00
  • "Do you really want to have conditional logic in constructing a class definition?" Yes. I come from JavaScript (I am quite experienced with it). I am a total beginner with TypeScript. Commented Nov 17, 2016 at 20:01
  • I'm quite sure this is not possible, but could you elaborate on your use-case? I'm not totally convinced that you are actually looking for something like C# preprocessor directives here :) Commented Nov 17, 2016 at 20:07
  • So as you accepted Ryans answer, I guess you wanted to add a property to an object through a class definition and that you didn't mind the class always having that property defined as optional. Commented Nov 17, 2016 at 20:24
  • @Alex, yes. Thank you for your help. Commented Nov 17, 2016 at 20:38

1 Answer 1

4

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',
            };
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.