entelect logo

BEE123 React Type safety

Should we add type safety? If so, how strict?

25 Aug 2020

Entelect + BEE123
BEE123 React Type safety

Type safety

Javascript is a mess

Entelect + BEE123
BEE123 React Type safety
var bob = { name: 'bob', age: 3 };
var fred = { name: 'fred', age: '5' };

var totalAge = bob.age + fred.age;
console.log(totalAge);
// error, 8, 35 
    
Entelect + BEE123
BEE123 React Type safety
var bob = { name: 'bob', age: 3 };

var temp = bob.calculateLifeExpectancy();
// This will throw an error
    
Entelect + BEE123
BEE123 React Type safety

Possible solutions

  • Typescript
  • Flow
  • Proptypes
Entelect + BEE123
BEE123 React Type safety

Typescript

typescript error
Entelect + BEE123
BEE123 React Type safety

Typescript Errors

typescript error
Entelect + BEE123
BEE123 React Type safety
export class TranslationKeyService {
  constructor(httpService) { }

  get(guid) {
    // ...
  }
}
export class TranslationKeyService implements ICrudService<TranslationKeyViewModel> {
  constructor(private httpService: HttpService) { }

  get(guid: string): Observable<ResultWithValue<TranslationKeyViewModel>> {
    // ...
  }
}
Entelect + BEE123
BEE123 React Type safetytypescript intelli

typescript intelli
Entelect + BEE123
BEE123 React Type safety

Typescript downsides

  • Additional build time
  • It can be very finicky
  • Can be cheated
Entelect + BEE123
BEE123 React Type safety

Typescript being finicky

// This will break your build
changePlatform = (plat) => {
    // logic here
}
// This will please the Typescript gods
changePlatform = (plat: PlatformType) => {
    // logic here
}
Entelect + BEE123
BEE123 React Type safety

Cheating Typescript

// This is cheating
changePlatform = (plat: any) => {
    // logic here
}
Entelect + BEE123
BEE123 React Type safetyflow logo
Entelect + BEE123
BEE123 React Type safety

Flow types in comments

// @flow

function greet(greeting /*: string*/) /* : string */ {
  return greeting;
}
Entelect + BEE123
BEE123 React Type safetydisappointed

Video 🔗

Entelect + BEE123
BEE123 React Type safety

Proptypes

Entelect + BEE123
BEE123 React Type safety
import React from 'react';
import PropTypes from 'prop-types';
 
class MyComponent extends React.Component {
  render() {
    // ... do things with the props
  }
}
 
MyComponent.propTypes = {
    param1: PropTypes.array,
    param2: PropTypes.bool,
    param3: PropTypes.func,
}
Entelect + BEE123
BEE123 React Type safety

Summary

  • Typescript is good
  • Flow is a disappointment
  • Proptypes is ok
Entelect + BEE123
BEE123 React Type safety

End