Definite assignment
There are occasions, however, where we would like to declare a variable using the let keyword and use it, before TypeScript thinks that it has been defined. Consider the following code:
let globalString: string; setGlobalString(); console.log(`globalString : ${globalString}`); function setGlobalString() { globalString = "this has been set"; }
Here, we have declared a variable named globalString. We then call a function named setGlobalString, which sets the value of the globalString variable. So, according to the logic of this code, the globalString variable is not undefined, and should contain a value at this stage. The next line of code logs the value of globalString to the console.
Unfortunately, the TypeScript compiler does not, and cannot, follow our execution path in order to validate whether a particular variable has been used before it has a value. As far as the compiler is concerned, we have declared the globalString variable, but have not assigned a value to it before it is used in the console.log. Compiling this code will produce the following error:
error TS2454: Variable 'globalString' is used before being assigned.
To cater for this scenario, we can use an assignment assertion syntax, which is to append an exclamation mark (!) after the variable that has already been assigned. There are two places that we can do this in order to allow our code to compile.
The first is in the declaration of the variable, as follows:
let globalString!: string;
Here, we have appended an exclamation mark to the declaration of the globalString variable. This tells the compiler that we are asserting that the variable has been assigned, and that it should not generate an error if it thinks that it has been used before being assigned.
The second place we can do an assignment assertion is where the variable is actually used, so we could modify our console.log function as follows:
console.log(`globalString : ${globalString!}`);
Here, we are using an assignment assertion where the globalString variable is being used by appending an exclamation mark to the variable.