Filling my gaps
As a growing software engineer, I am becoming increasingly aware of areas in the code that I used to ignore. I chose to ignore these areas similar to how a teenager that is excited to learn how to drive would. I wanted to get on the road as quickly as possible, nevermind that I did not know how to change a tire or know when I should see a mechanic for that sound I kept hearing. Now that I have a stable job, I feel ashamed of these areas that I lack knowledge of and want to do the responsible thing by filling my knowledge gaps. So today I read some Typescript documentation.
Definite Assignment Assertion
I often use ‘!’s in typescript code that just makes the code work when there is a compiler error. But the maneuver is mostly a guess on my part, akin to looking at other people during a workout class. I read through the documentation and learned that it is a feature for typescript, called Definite Assignment Assertion. The following is from the official Typescript docs:
let x: number;
initialize();
console.log(x + x);
function initialize() {
x = 10;
}
At first glance, this looks like a legal typescript move. We declare that x has a type of number, and we initialize it using the method initialize(). It would be correct to expect that this code works, and that the console log outputs the value 10.
However, typescript will complain (I don’t know why yet) that the variable ‘x’ is used before being assigned. Using a ‘!’, we can assert that x is really assigned before it is used.
let x!: number;
initialize();
console.log(x + x);
function initialize() {
x = 10;
}
By using the definite assignment assertion operator, we tell the compiler that it will not be undefined when we run the code.