How to Properly Use ‘!’ (Exclamation Mark) in TypeScript

Updated: January 8, 2024 By: Guest Contributor Post a comment

Overview

The exclamation mark, while often viewed with the spirit of surprise or alarm, holds a quite technical and purposeful role in the pragmatic world of TypeScript. This bespeaks its quiet yet assertive task in asserting presence where uncertainty may lurk.

Understanding Non-null Assertion

In TypeScript, the exclamation mark (!) is a non-null assertion operator. It is a suave gentleman’s way of telling the compiler to hold its horses — to trust that one has a firm grasp on the reins and that the steed of a variable’s value is surely no phantom.

let variableMayBeNull: string | null = 'Im certain this exists!';
console.log(variableMayBeNull!.length);

This tidbit tells the tale that, although the established contract lets null afoot under normal circumstances, we, as the variable’s kin custodian, have ascertained its existence, pooh-poohing the chance of null.

The Bang of Post-fix Operations

The syntax in claiming certitude is a straightforward affair. You’ve just to postfix the variable in question with an exclamation, just as such:

interface Hat {
    feathers?: string;
}

let clemensHat: Hat = {};
clemensHat.feathers! = 'Elegant Plume';

Now the script adds nothing else but our guarantee that the property ‘feathers’ is to be decked as splendidly as any top hat for a Sunday promenade. Yet we’d be wise to tread lightly, for assurance without substance leads but to folly.

Advanced Acrobatics with Functions

The wisdom of the exclamation mark is seen in the actions of functions too, for a function may assert its return to never be as null as a riverbed in drought:

function surelyReturnsSomething(): string | null {
    if (weHaveLetter) {
        return 'A Letter from Mark';
    }
    return null;
}

let letter = surelyReturnsSomething()!;
console.log(letter.toUpperCase());

Here, setting the carriage ahead of the horse, predicting the return of a ‘string’ with such certainty might trip a gentleman in sophistry if the function deems fitting to return null in surprise.

Vigilance against the Vainglory of Assumptions

It befits a programmer, much similar to a riverboat captain, to wield the exclamation with discretion for indifference can birth egregious outcomes. The exclamation mark is no shorthand for data-validation, nor should it supplant sagacious checks; it serves merely as our concentrated word to the compiler that comes from meticulous scrutiny, hinting it to forgo its fretful propensities.

Type Assertions and the Exclamation Point

Not unlike the manner of pointed hats to suggest a wizard’s presence, the pointed mark paired with types has ample say. You may assert types with an explicit syntax, but remember, type assertion is distinct from the non-null assertion as one might distinguish a Mississippi steamboat from a Nantucket whaler.

Conclusion

Mark well these words about our exclamatory comrade in TypeScript. Employ it properly and your code shall run as true as a well-oiled locomotive, but misuse it at your peril, for assuming a bad fact makes one as foolish as a gambler bettin’ his last dime on a hunch. Let it be your conscious declaration, never an unconscious assumption.