Explicitly declaring interface makes it easier to understand the intentions behind code • By realtime code check, get fast feedback cycle of developing JavaScript
cycle (monitor changes, and since only the ones that have changed are checked for the second time and thereafter) • Not AltJS (It provides only type annotation)
{ … handleCreateComment(comment: string) { CommentActions.create(1); } } $ flow scripts/CommentContainer.jsx:27 27: CommentActions.create(1); ^ number. This type is incompatible with the expected param type of 14: create(comment: string) { ^^^^^^ string. See: scripts/CommentActions.js:14 Found 1 error create method is expected to receive string
'flux/utils'; import type { ActionTypes } from './CommentActions'; import Dispatcher from './Dispatcher'; export type Comment = {id: number, comment: string }; export type State = Comment[]; let count = 0; class CommentStore extends ReduceStore<State> { getInitialState(): State { return []; } reduce(state: State, action: ActionTypes): State { switch (action.type) { case 'create': return state.concat({ id: ++count, comment: action.comment }); case 'delete': const deleteId = action.id; return state.filter((v) => v.id !== deleteId); default: return state; } } } const instance = new CommentStore(Dispatcher); export default instance; import UnionTypes of Actions set action’s type as UnionTypes enable to narrow down UnionTypes can access only narrowed type’s property
{id: number, comment: string }; export type State = Comment[]; //… class CommentStore extends ReduceStore<State> { //… } define state of Store give State as generics declare module 'flux/utils' { declare class ReduceStore<T> { getState(): T; getDispatchToken(): string; } declare class Container { static create(): any; } //… } use generics for public API
{ Comment } from './CommentStore'; type State = { comments: Comment[] }; class CommentContainer extends React.Component { state: State; //… static calculateState(_prevState: State): State { const comments = CommentStore.getState(); return { comments }; } //… } can get typed state of Store