Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify function return type

Tags:

powershell

How do I specify the return type in a powershell function?

function getSomeString {
    return "hello world"
}
$xyz = getSomeString()  # <--- IDE does not recognize $xyz as a string
like image 950
birgersp Avatar asked Jul 24 '26 04:07

birgersp


1 Answers

Before getting to the answer, I should point out that PowerShell commands do NOT have static return types!

In terms of I/O, commands in PowerShell are like little black boxes - you send 0 or more input objects in one end, and 0 or more outputs object are emitted at the other end - the type(s) of which may vary.


That being said, you can add a type inference hint to your function by adding an [OutputType] attribute decorator to the function's param block:

function Get-SomeString {
    [OutputType([string])]
    param()
    
    return "hello world"
}

$xyz = Get-SomeString # Tools can now infer type of `$xyz`

Again, this is a hint, not a guarantee - you can lie if you want to:

function Get-Integers
{
  [OutputType([int[]])]
  param()

  if((1..10 |Get-Random) -gt 7){
    return "lol, I'll do what I want"
  }

  return 1,2,3
}

$f = Get-Integers

In this case, Get-Integers will return a [string] 30% of the time, but the IDE will always act like both $f and Get-Integers resolves to an array of [int]'s - because that's what we told it to expect.

like image 138
Mathias R. Jessen Avatar answered Jul 28 '26 16:07

Mathias R. Jessen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!