1
votes

In Power Query (M) I've found 2 ways to declare types: myVar as type or type text

Each seems to apply to different contexts. For example:

Table.AddColumn(myTable, "NewName", each [aColumn], type text)

or

MyFunc = (aParam as any) as date => Date.From(aParam)

However, this doesn't work as I expect for more complex types, like {text} or {number}, which would be a list of only text values or only numbers. I can use these types with the type syntax, but not the as type syntax.

Why/not?

Also, does declaring types in M have any performance impact, or is it just to raise an error if an incorrect type is passed/returned?

1

1 Answers

2
votes

Declaring types in "M" should normally have very little performance impact, and will make your functions more "self-documenting".

When a function is invoked, the function arguments type "kind" is checked, and not the custom, full type definition. So passing a list of numbers to a function that expects list-of-text doesn't cause any errors. You can see that with some "M":

let
    FunctionType = type function (l as { text }) as any,
    UntypedFunction = (l) => l{0},
    TypedFunction = Value.ReplaceType(UntypedFunction, FunctionType),
    Invoked = TypedFunction({0, 1, 2})
in
    Invoked

Not checking the recursive type is good for performance because checking each element of a list would require looping through the whole list.

When you write a function value like (l) => l{0} you can only use primitive types like as list and not as { text }. I think this limitation is intended to guide the function author into not putting type restrictions that won't be honored by the function.

You can read more about what the syntax allows in the Language Specification. (If that link dies you should be able to follow the PDF link from MDSN.)