How works OutputType attribute?
function test
{
[OutputType([Bool])]
Param ($a)
return $a
}
$one = test 1
$two = test 0
$one.GetType() # Int32
$two.GetType() # Int32
I expected $one is true, $two is false.
CodePudding user response:
To build on the helpful comments by Abraham Zinala and Mike Shepard:
As the conceptual about_Functions_OutputTypeAttribute help topic indicates:
The
[OutputType()]
attribute does not control a function or script's actual output data type.PowerShell offers no way to declare an enforced "return type" the way languages such as C# do: while it makes sense to constrain and document what a function or script outputs ("returns"), it is technically free to output any number of objects, of any type, simply by writing to the success output stream.
By contrast, you can enforce the data type of input provided to a function or script, namely by type-constraining its parameter definitions; for instance, you could ensure that arguments passed to your
-a
parameter are Booleans to begin with, by replacingparam($a)
withparam([bool] $a)
, as Abraham notes - see the conceptual about_Functions_Advanced_Parameters help topic.
Instead, the
[OutputType()]
attribute only has informational character:It adds metadata to a function definition listing the output type(s), which features such as PowerShell's help system and tab-completion can make use of.
It is up to the function / script author to make sure that the types listed via
[OutputType()]
reflect the actual output data types.- Therefore, the information may be incorrect - as it was in your case, accidentally.
Therefore, your function needs to ensure that the desired data type is output as part of the output statement:
function test
{
[OutputType([bool])]
Param ($a) # $a is allowed to be of any type (no type constraint present)
# Output a [bool] explicitly.
# Note: No strict need for `return` here,
# thanks to PowerShell's implicit output behavior.
[bool] $a
}