TypeScript + React
An in depth look
The appeal of TypeScript + React
It all comes down to static typing.
TypeScript is just JavaScript - just with the seat belt fastened.
Static typing advantages
- working with large code bases is hard in general
- when using a dynamic language, it takes more discipline
- naming and other conventions
- this is how linters were born
- but TS is not a replacement for a linter, there is `tslint`
- catches a class of easy to make, but hard to find bugs
- spelling errors for instance
- enables smarter tooling
- refactoring is not find in files anymore
- the code is self documenting
About TypeScript
- created by
M$Microsoft in 2012 - created by Anders Hejlsberg
- open source from the beginning, hosted on github
- follows ES spec closely
- quite open and inclusive, adopted by Angular2 and Dojo2
- has great IDE support
TypeScript cool features
- interfaces
- generics
- enums
- advanced types
- method access modifiers
Compiler related:
- type definiton files
- bundles normal JS files
Interfaces
- anonymous interfaces
- can describe function types
- can extend a class
- can be generic
Advanced types
- union types
- type guards
- typeof
- instanceof
- intersection types
- type aliases (can be generic)
- string literal types
React with TypeScript
- React has 1st class support in TS
- TS compiler has support for React since v 1.6 (sept 2015)
- TS compiler can transpile the JSX code to JavaScript
- new React fixes with every new TS release
- interfaces for props and state
- component attribute checks
- is modeled after how JSX is transformed
- no need for prop types
- works with the usual tools: webpack
- TypeScript 1.8
- supports stateless function components
- simplified props type management
Tips, tricks and gotchas
- lazy object initialization
- calling setState() with less keys
- missing type definition files
- provide a dummy definition
- write a proper .d.ts file (starting from the API doc)
TS compared to Flow
There is a bit of overlap.
TypeScript advantages:
- wider adoption, more mature, great tool support
- more features: enums, union types
- lots of type definition files
- Flow doesn't work on Windows
Flow advantages:
- incredibly smooth transition
- super fast
Advices
- use tslint and try to be as strict as possible
- try to avoid any as it defies the purpose of TS
- use the class construct for organizing the code
- always prefer composition to inheritance
- specially with React
- try to follow the TypeScript coding standards
- https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines
End
TypeScript + React
By kenjiru
TypeScript + React
An in depth look
- 608