In this article I’ll show you how to create types from text in Power Query, enabling you to dynamically change types via functions for example. It’ll come out as a custom Type.FromText function which has been asked for in the comments of this article: https://www.thebiccountant.com/2017/01/09/dynamic-bulk-type-transformation-in-power-query-power-bi-and-m.
Problem
To transform a column to type text can be done like so:
Table.TransformColumnTypes(Source,{{"Column1", type text}})
This transforms the “Column1” from table “Source” to type text. Now, if you want to make the type dynamic and move it to a function parameter like so:
(VariableType as type) => Table.TransformColumnTypes(Source,{{"Column1", VariableType}})
This returns a function dialogue as follows:
Type in “type text” like so:
You’ll receive the following error-message:
Look at the M-code that has been generated in the formula bar: “type text” is in quotes and this makes it a text-string. The function dialogue doesn’t give an option to actually select or enter a type expression. This would be without quotes like so:
MyFunction( type text )
So if I aim to feed my function a text value to dynamically create a type from it, I need a function that returns a type and accepts a text value to identify the actual type.
Solution
I couldn’t find a native function for it, so using Expression.Evaluate as the rescue here:
Table.TransformColumnTypes(Source,{{"Column1", Expression.Evaluate("type text", [type text = type text])}})
This allows me to use a text expression as the type selector. But hey: What’s the record in the second function argument?: Now we have some type-expressions there! So nothing really gained …
(Edit: If you wonder why I haven’t used #shared as a dynamic version for the record, please read this article: https://www.thebiccountant.com/2018/05/17/automatically-create-function-record-for-expression-evaluate-in-power-bi-and-power-query/ )
The Type.FromText Function
That’s where my new function kicks in: It includes all the writing necessary and you just have to copy the code and use it. It’s a function with one parameter (the textual representation of the type) that returns the said type.
Currently it only contains M’s primitive types, but I guess you’ve spotted the pattern and can adjust to other types by yourself if necessary.
Edit: Actually, as it turned out, I was overthinking the task a bit. Check out Daniil’s comment below for a simpler version: https://www.thebiccountant.com/2019/11/17/dynamically-create-types-from-text-with-type-fromtext/#comment-1507
Enjoy & stay queryious 😉
The post Dynamically create types from text with Type.FromText in Power Query and Power BI appeared first on The BIccountant.