I'd love to see a strict mode or some other language feature to enforce strict typing (and at the same time remove the implicit casting that occurs sometimes).
Things like avoiding this:
[string] $test = ""
$test = @{}
$test
System.Collections.Hashtable
[string] $test = ""
$test = 7
$test
7
$test.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
PowerShell is a script language and it does huge implicit castings for better UX.
Agreed -- but as we start to use PowerShell for programming it would be nice to limit some of the casting, or be able to add linter checks with type hints in order to reduce unexpected run-time behavior.
Figured I'd file an issue to see what others think :)
Some of that could be done quite well by PSScriptAnalyzer rules, I suppose? 馃
I also thought about this. When I explicitly tell PS that the variable is a string, it's type should never change.
That is the case already:
[string]$variable = "hello"
$variable = Get-Date
$variable.GetType() # string
What can cause some confusion, however, is the implicit conversions that often take place.
[string] is especially tricky with respect to the implicit conversions, because _anything_ can be converted to a string in PowerShell.
The closest approximation of what you're asking with the current features is to use a [ValidateScript()] attribute (which, although not widely known, can also be applied to _variables_ not just to _parameters_ (parameter variables):
PS> [ValidateScript({ $_ -is [string] })] $foo = 'hi'; $foo = 42
MetadataError: The variable cannot be validated because the value 42 is not a valid value for the foo variable.
The primary problem is that this is still only enforced at _runtime_.
The secondary problem is the unhelpful abstract error message; even though ValidateScript now supports an ErrorMessage property, it isn't used (it is only used for _parameters_) - arguably a bug.
Some of that could be done quite well by PSScriptAnalyzer rules, I suppose?
The problem is that presumably more often than not you _do_ want PowerShell's implicit conversions, as they are typically helpful. Warning about every type discrepancy could get very distracting.
This issue has been marked as answered and has not had any activity for 1 day. It has been closed for housekeeping purposes.