#Suggested `[OutputType]` for `Object` and `Write-Host` ?

6 messages · Page 1 of 1 (latest)

blazing drum
#

If you have a command that's either

  • object when using -PassThru
  • otherwise no output, explicit write-host

Is there a good way to declare the OutputType ? I tried several variations of the parameter sets, but none seemed to work perfectly.

In the past I think there was an issue using void and object together, for completions . But it's improved a lot so maybe it's good now
?

Import-Module Pansies
function H1 {
    [OutputType( [System.Void], ParameterSetName = '__AllParameterSets' )]
    [OutputType( [PoshCode.Pansies.Text], ParameterSetName = 'OutObject' )]
    [CmdletBinding( DefaultParameterSetName = '__AllParameterSets')]
    param(
        [Parameter(Mandatory, Position = 0, ParameterSetName = '__AllParameterSets')]
        [string] $Text,

        # Instead of writing to host, return result of (New-Text)
        [Parameter(Mandatory, ParameterSetName = 'OutObject')]
        [switch] $PassThru
    )
    $obj = $Text | Pansies\New-Text -Fg 'gray40' -bg 'gray20'
    if( $PassThru ) { return $Obj }
    $Obj | Write-Host
}

H1 'sdfds'

H1 'sdfds' -PassThru
    | Write-Verbose -Verbose

H1 'sdfds' -PassThru
    | Write-Host

(Gcm h1).OutputType |ft -AutoSize
<#
    Name                  Type
    ----                  ----
    System.Void           System.Void
    PoshCode.Pansies.Text PoshCode.Pansies.Text
#>

( h1 'sdfdfs' -PassThru).<Tab>
    # 👍 : Generates correct [Pansies.Text] completions

( h1 'sdfdfs').<Tab>
    # 🙈 : Instead of nothing, generates [Pansies.Text] completions
orchid citrus
#

As this is really feeding docs and intellisense...

I would only have [OutputType( [PoshCode.Pansies.Text] )] and would ignore void entirely for the purposes of declaring what it emits.

I would only use void for commands that have no output at all.

ionic vortex
#

Hmm. Would you prefer to have no completions on the "void" case? I guess that would be good. Should psreadline or the like just roll through all completions for any of the output types or should it read the Ast and pick?

blazing drum
#

Possibly the metadata could be useful for a pscriptanalzyer rule ?

Have you ever used an [Attribute] that marks a function as using write-host ?

For PSReadLine completions, there's probably not a good alternative
Although it does work for variables.

$x = $Null
 
( $x ).<tab>       # <- shows 0 completions
$x.<tab>           # <- shows 0 completions

($x ?? '').<tab>   # <- shows [string] completions
orchid citrus
#

I very occasionally use attributes to mark functions, but typically only when I'm doing something particularly strange within a module (like selectively making commands available to a runspace I'm spinning up).