Is PowerShell a strongly-typed language?

Chris Sutton picture Chris Sutton · Sep 22, 2008 · Viewed 9.3k times · Source

PowerShell is definitely in the category of dynamic languages, but would it be considered strongly typed?

Answer

JacquesB picture JacquesB · Sep 22, 2008

There is a certain amount of confusion around the terminlogy. This article explains a useful taxonomy of type systems.

PowerShell is dynamically, implicit typed:

> $x=100
> $x=dir

No type errors - a variable can change its type at runtime. This is like Python, Perl, JavaScript but different from C++, Java, C#, etc.

However:

> [int]$x = 100
> $x = dir
Cannot convert "scripts-2.5" to "System.Int32".

So it also supports explicit typing of variables if you want. However, the type checking is done at runtime rather than compile time, so it's not statically typed.

I have seen some say that PowerShell uses type inference (because you don't have to declare the type of a variable), but I think that is the wrong words. Type inference is a feature of systems that does type-checking at compile time (like "var" in C#). PowerShell only checks types at runtime, so it can check the actual value rather than do inference.

However, there is some amount of automatic type-conversion going on:

> [int]$a = 1
> [string]$b = $a
> $b
1
> $b.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

So some types are converted on the fly. This will by most definitions make PowerShell a weakly typed language. It is certainly more weak than e.g. Python which (almost?) never convert types on the fly. But probably not at weak as Perl which will convert almost anything as needed.