SharePoint developers - we do like GUIDs, don’t we. We all read RFC4122 both once and twice. And now with SharePoint Framework and the goal to embrace all them Macintosh and open source people - they gotta have their fair share of GUIDs.
And to aid with that the SharePoint Framework got some really nice GUID features, although a bit unpolished as you might notice - but this is all preview bits at the time of writing.
The Guid class
First of all we must have the option to create GUIDs. There might be a situation that you need to store something really, really unique - to help with the we do have the Guid class in the @microsoft/client-sp-base module. This class both allows you to create new Guids, parse Guids and validate Guids.
This is how you import the Guid class:
import { Guid } from '@microsoft/sp-client-base';
Then to create a Guid, you use the code below. The newGuid method can take an optional parameter if you need to create a custom random generator. By default it generates a version 4 UUID, also known as a pseudo random UUID, which can be generated in a browser. I suggest you skip passing in custom random generators.
var guid: Guid = Guid.newGuid();
What if someone gives a “GUID” to you, can you trust it is a proper Guid, no you can’t you need to validate it. That can be done using the isValid method, which takes a string as in input.
if( Guid.isValid(' f0a1f189-dae4-49f5-8846-3a17429fd52') ) { alert('Valid') };
Then we finally also have a method to parse a string potentially containing a Guid, tryParse. The method will either return a Guid object or undefined.
var guid: Guid = Guid.tryParse('f0a1f189-dae4-49f5-8846-3a17429fd52');
The GuidHelpers class (@internal)
[Update 2016-09-20] - The GuidHelpers class is marked internal and will be removed in future builds of the SharePoint Framework.
There’s also another class in SharePoint Framework for Guids, the GuidHelpers class. This class lives in the @microsoft/sp-client-preview module. It has a set of similar function to generate and validate Guids, but it does not work with Guid objects, it uses strings instead. For instance the GuidHelpers.generateGuid() returns a string. Another issue is that the GuidHelpers.isValid() does not validate Guids the same way as the Guid.isValid does (issue #201 in the SPFx Repo).
At the moment (drop 3 of SPFx) I would stay away from the GuidHelpers class.
As usual there’s some code samples of this to be found in this Github repo: https://github.com/wictorwilen/spfx-nuggets
Happy GUIDing!