optional() function
@microsoft/fast-element/di.js > optional
optional() function
A decorator that allows you to optionally inject a dependency depending on whether the [[Key
]] is present, for example:
Signature:
optional: (key: any) => any
Parameters
Parameter | Type | Description |
---|---|---|
key | any | The key to optionally resolve. see on interactions with interfaces |
Returns:
any
Example 1
class Foo {
constructor( @inject('mystring') public str: string = 'somestring' )
}
container.get(Foo); // throws
would fail
Example 2
class Foo {
constructor( @optional('mystring') public str: string = 'somestring' )
}
container.get(Foo).str // somestring
if you use it without a default it will inject undefined
, so remember to mark your input type as possibly undefined
!