6 TypeScript Features I Can’t Live Without After Using Them!
Today, I’ll introduce some of the newer features and developments in TypeScript that I frequently use in my day-to-day work.
Defining properties directly in the constructor.
In TypeScript, you can directly define properties through constructor parameters. Let’s first take a look at the earlier approach:
class Note {
public title: string;
public content: string;
private history: string[];
constructor(title: string, content: string, history: string[]) {
this.title = title;
this.content = content;
this.history = history;
}
}
Using the shorthand syntax in TypeScript:
class Note {
constructor(
public title: string,
public content: string,
private history: string[]
){
// You don't need to write 'this.title = title' here anymore.
}
}
It may not look like a class with properties at first glance, but it indeed has them, utilizing TypeScript’s shorthand form — defining properties directly through constructor parameters.
This shorthand syntax accomplishes several things:
- Declares a constructor parameter and its type.
- Declares a public property with the same name.
- Initializes this property with the corresponding parameter value when we create an instance of this class.
Nullish Coalescing
Actually, ??
doesn’t mean much; it’s just Nullish Coalescing. It may sound a bit confusing, so let’s dive right into the code.
const i = undefined
const k = i ?? 5
console.log(k) // 5
// 3.9.2 compiling
const i = undefined;
const k = i !== null && i !== void 0 ? i : 5;
console.log(k); // 5
At this point, you’re probably thinking, ‘Why not just do it like this?’
let k = i || 5
While this approach works, don’t you think it’s a bit imprecise? What if ‘i’ is 0?
Private Class Fields
TypeScript 3.8 will support ECMAScript private fields, so don’t confuse them with TypeScript’s ‘private’ modifier.