1

I'd like to declare a number on a class as optional, using the '?' operator.

export class DummyClass {
    dummyId?: number;   
}

Visual Studio doesn't let me compile because of a '; is expected. Unexpected token' error. However when I e.g. declare a function or interface, it works without problems:

void(sup?: number) {} // nothing to complain here

Are there some rules about this? Or is something wrong with Intellisense?

1

1 Answer 1

2

If you don't require that property to be set, you can just have:

export class DummyClass {
    dummyId: number;   
}

In this example, dummyId is undefined until someone sets a value. Essentially, properties need no special character to say "you don't have to set me".

When you accept an argument, you can make it optional. This is true of methods and constructors:

export class DummyClass {
    constructor(public dummyId?: number) {

    }


    doSomething(dummyId?: number) {

    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's also true for interfaces.

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.