TypeScript Definite Assignment Operator (!)
Sometimes values in TypeScript are not used until they are set after they are created. An example of this in the Dart language would be the late assignment keyword.
Check out the code below:
var myGlobalString: string; // undefined
// Here we use the setGlobalString function to assign a string to myGlobalString
setGlobalString('Assigning a string');
// The compiler will throw an error.
// error TS2454: Variable 'myGlobalString' is used before being assigned
console.log(`myGlobalString = ${myGlobalString}`);
function setGlobalString(value: string) {
myGloblString = value;
}
We know from our code that myGlobalString is indeed being assigned before our console.log. However the compiler doesn’t know this to be true.
To remedy this we can use the definite assignment assertion operator (!) to tell the compiler that it will not be undefined for null when we run the code:
// Using ! here will escape this error
console.log(`myGlobalString = ${myGlobalString!}`);
Similarly we could also use the definite assignment assertion operator (!) when we define the variable, to tell the compiler that wherever we use this variable, it will be defined before we use it:
var myGlobalString!: string;
Although we have the ability to use this operator (!), it is definitely something to be avoided as much as possible when writing clean code to avoid mistakes.
If you’re interested in playing with this code, please check out the link to the repl here:
Thanks for reading! 👋🏽😎