It is possible for the property to be optional, containing a function as its value if it is set.
This can be essentially expressed in shorthand as:
{
start: (() => void) | undefined
}
This indicates that the start
property may or may not have a function assigned to it. Therefore, when calling this function, you need to account for the scenario where it does not exist:
if (foo.start) {
foo.start()
}
Alternatively, you can utilize the optional chaining operator, which is the opposite of the optional property operator:
foo.start?.()
It is recommended to avoid using the !
postfix operator in most cases, as it compels TypeScript to allow potentially unsafe operations. If the property truly is undefined
, forcibly invoking it could lead to a runtime error.
Here is a more comprehensive example:
class Foo {
start?(): void
constructor(isStartable: boolean) {
if (isStartable) {
this.start = () => console.log('starting!')
}
}
}
const nonStartable = new Foo(false)
// The start method will not be invoked.
if (nonStartable.start) nonStartable.start()
const startable = new Foo(true)
// The start method will be called.
if (startable.start) startable.start()
// Running this code will log "starting!" exactly once.
Playground