Skip to content

Instantly share code, notes, and snippets.

@JulianG
JulianG / avoiding-non-null-assertions.md
Last active October 11, 2020 12:05
Avoiding the Non-null-assertion Operator in React + Mobx + Typescript Projects

Avoiding Non-null-assertion Operator in React + Mobx + Typescript Projects

Today I learned something at work. I am new to MobX and I had to make changes to a React + Typescript + MobX project. I noticed the props of some React components were marked as optional, and I was told it was because of how the dependency injection worked.

The Problem

When injecting MobX stores into React components in Typescript, the recommended approach in MobX docs involves declaring optional props (?). This results in having to perform null checks when accessing an injected store, and MobX recommendeds using the non-null assertion operator (!).

interface BananaProps {

Keybase proof

I hereby claim:

  • I am juliang on github.
  • I am juliang (https://keybase.io/juliang) on keybase.
  • I have a public key ASC6w3PW2ig7pBT3EOlvCiqZnC4W60rPOG57MHiE4C807wo

To claim this, I am signing this object:

/*
tslint:disable no-any
tslint:disable no-empty
*/
class MutedConsole implements Console {
memory: any;
Console: NodeJS.ConsoleConstructor;
assert(test?: boolean, message?: string, ...optionalParams: any[]): void { }
@JulianG
JulianG / ObjectPool.as
Last active December 10, 2015 16:28
General purpose AS3 Object Pool class
package
{
/**
* ObjectPool Class
* @author Julian
*/
public class ObjectPool
{
private var _list:Array;