Reputation: 2229
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?
Upvotes: 1
Views: 488
Reputation: 250972
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) {
}
}
Upvotes: 2