Skip to content

Instantly share code, notes, and snippets.

@hmil hmil/nullables.ts
Created Aug 1, 2017

Embed
What would you like to do?
The one true way to deal with nullables in TypeScript.
/**
* The one true way to deal with nullables in TypeScript.
*
* This code demonstrates a nice design pattern to deal with nullable
* values in TypeScript. In my blog post, I describe how sane practices
* around null values involved in both synchronous and asynchronous workflows
* enhance the quality of the code without any downside.
*
* http://blog.hmil.fr/2017/08/deal-with-nullables-like-theyre-not-even-here-good-coding-practices-in-typescript/
*
* This demo was compiled with typescript 2.4.1 and tested in NodeJS v8.1.3.
* You will need the following tsconfig.json in order to compile:
*
```tsconfig.json
{
"compilerOptions": {
"strictNullChecks": true,
"target": "es5",
"lib": [
"dom", "es2015"
]
}
}
```
*/
class User {
constructor(
public name: string) {
}
/** A user may want to fetch her introduction sentence from an async source so
* we use a callback to handle the asynchronous execution flow.
*/
public introduce(cb: (msg: string) => void): void {
setImmediate(() => {
cb(`Hello, my name is ${this.name}`);
});
}
}
class App {
_user?: User;
public login(user: User): void {
this._user = user;
}
private get user(): User {
if (!this._user) {
throw new Error('No user is logged in!');
}
return this._user;
}
public renameUser(newName: string): void {
this.user.name = newName;
}
public introduceUser(): Promise<string> {
return new Promise<string>(resolve => {
this.user.introduce((s) => resolve(s));
})
}
}
const app = new App();
app.introduceUser().then(console.log, console.error);
app.login(new User('John'));
app.introduceUser().then(console.log, console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.