Created
August 1, 2017 15:00
-
-
Save hmil/d4034d013dacb198992567cbe31150c5 to your computer and use it in GitHub Desktop.
The one true way to deal with nullables in TypeScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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