Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support typescript #157

Merged
merged 7 commits into from
Oct 14, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ dist
coverage
.nyc_output
npm-debug.log
test/typescript/*.map
test/typescript/*.jsx
79 changes: 79 additions & 0 deletions fetch.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
declare type HeadersInit = Headers | string[][] | { [key: string]: string };
declare class Headers {
constructor(init?: HeadersInit);

append(name: string, value: string): void;
delete(name: string): void;
get(name: string): string; // | null; (TS 2.0 strict null check)
has(name: string): boolean;
set(name: string, value: string): void;

// WebIDL pair iterator: iterable<ByteString, ByteString>
entries(): IterableIterator<[string, string]>;
forEach(callback: (value: string, index: number, headers: Headers) => void, thisArg?: any): void;
keys(): IterableIterator<string>;
values(): IterableIterator<string>;
[Symbol.iterator](): IterableIterator<[string, string]>;
}

type BodyInit = Blob | ArrayBufferView | ArrayBuffer | FormData | string;
interface Body {
bodyUsed: boolean;
arrayBuffer(): Promise<ArrayBuffer>;
blob(): Promise<Blob>;
formData(): Promise<FormData>;
json(): Promise<any>;
text(): Promise<string>;
}

declare type RequestInfo = string;
interface RequestInit {
method?: string;
headers?: HeadersInit;
body?: BodyInit;
referrer?: string;
referrerPolicy?: ReferrerPolicy;
mode?: RequestMode;
credentials?: RequestCredentials;
cache?: RequestCache;
redirect?: RequestRedirect;
integrity?: string;
window?: any;
}

type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video";
type RequestDestination = "" | "document" | "embed" | "font" | "image" | "manifest" | "media" | "object" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "worker" | "xslt";
type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors";
type RequestCredentials = "omit" | "same-origin" | "include";
type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached";
type RequestRedirect = "follow" | "error" | "manual";
type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";

declare class Response {
constructor(body?: BodyInit, init?: ResponseInit);

static error(): Response;
static redirect(url: string, status?: number): Response;

type: ResponseType;
url: string;
redirected: boolean;
status: number;
ok: boolean;
statusText: string;
headers: Headers;
body: any;
trailer: Promise<Headers>;

clone(): Response;
}
declare interface Response extends Body {}
interface ResponseInit {
status?: number;
statusText?: string;
headers?: HeadersInit;
}

type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect";

export default function fetch(url: RequestInfo, init?: RequestInit): Promise<Response>;
6 changes: 5 additions & 1 deletion fetch.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
require('whatwg-fetch');
module.exports = self.fetch.bind(self);

Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = self.fetch.bind(self);
120 changes: 120 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import {
Reducer,
Action,
ReducersMapObject,
Dispatch,
MiddlewareAPI
} from 'redux';

export interface onActionFunc {
(api: MiddlewareAPI<any>): void;
}

export interface ReducerEnhancer {
(reducer: Reducer<any>): void
}

export interface Hooks {
onError?: (e: Error, dispatch: Dispatch<any>) => void;
onAction?: onActionFunc | onActionFunc[];
onStateChange?: () => void;
onReducer?: ReducerEnhancer;
onEffect?: () => void;
onHmr?: () => void;
extraReducers?: ReducersMapObject;
}

export type DvaOption = Hooks & {
initialState?: Object;
history?: Object;
}

export interface EffectsCommandMap {
put: <A extends Action>(action: A) => any;
call: Function;
select: Function;
take: Function;
cancel: Function;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里需要定义 return 类型吗

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

感觉这里不是很重要,就偷懒了。

[key: string]: any;
}

export type Effect = (action: Action, effects: EffectsCommandMap) => void;
export type EffectType = 'takeEvery' | 'takeLatest' | 'watcher' | 'throttle';
export type EffectWithType = [Effect, { type : EffectType }];
export type Subscription = (api: SubscriptionAPI, done: Function) => void;
export type ReducersMapObjectWithEnhancer = [ReducersMapObject, ReducerEnhancer];

export interface EffectsMapObject {
[key: string]: Effect | EffectWithType;
}

export interface SubscriptionAPI {
history: HistoryModule.History;
dispatch: Dispatch<any>;
}

export interface SubscriptionsMapObject {
[key: string]: Subscription;
}

export interface Model {
namespace: string,
state?: any,
reducers?: ReducersMapObject | ReducersMapObjectWithEnhancer,
effects?: EffectsMapObject,
subscriptions?: SubscriptionsMapObject,
}

export interface RouterAPI {
history: HistoryModule.History;
app: DvaInstance;
}

export interface Router {
(api?: RouterAPI): JSX.Element | Object;
}

export interface DvaInstance {
/**
* Register an object of hooks on the application.
*
* @param hooks
*/
use: (hooks: Hooks) => void,

/**
* Register a model.
*
* @param model
*/
model: (model: Model) => void,

/**
* Config router. Takes a function with arguments { history, dispatch },
* and expects router config. It use the same api as react-router,
* return jsx elements or JavaScript Object for dynamic routing.
*
* @param router
*/
router: (router: Router) => void,

/**
* Start the application. Selector is optional. If no selector
* arguments, it will return a function that return JSX elements.
*
* @param selector
*/
start: (selector?: HTMLElement | string) => any,
}

export default function dva(opts?: DvaOption): DvaInstance;

/**
* Connects a React component to Dva.
*/
export function connect(
mapStateToProps?: Function,
mapDispatchToProps?: Function,
mergeProps?: Function,
options?: Object
): Function;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

export function connect(
  mapStateToProps?: Function,
  mapDispatchToProps?: Function,
  mergeProps?: Function,
  options?: Object
): Function(JSX.Element); // 这样?写法好像不对,因为如果不指定参数不会检测的吧,这个地方是强关联

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok。

8 changes: 6 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
module.exports = require('./lib');
module.exports.connect = require('react-redux').connect;
Object.defineProperty(exports, "__esModule", {
value: true
});

exports.default = require('./lib');
exports.connect = require('react-redux').connect;
13 changes: 13 additions & 0 deletions mobile.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import dva from './index';

export default dva;

/**
* Connects a React component to Dva.
*/
export function connect(
mapStateToProps?: Function,
mapDispatchToProps?: Function,
mergeProps?: Function,
options?: Object
): Function;
8 changes: 6 additions & 2 deletions mobile.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
module.exports = require('./lib/mobile');
module.exports.connect = require('react-redux').connect;
Object.defineProperty(exports, "__esModule", {
value: true
});

exports.default = require('./lib/mobile');
exports.connect = require('react-redux').connect;
14 changes: 12 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"url": "https://github.com/dvajs/dva"
},
"homepage": "https://github.com/dvajs/dva",
"typings": "./index.d.ts",
"keywords": [
"dva",
"ant",
Expand All @@ -19,8 +20,13 @@
"framework",
"frontend"
],
"author": "chencheng <sorrycc@gmail.com>",
"authors": [
"chencheng <sorrycc@gmail.com> (https://github.com/sorrycc)"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/dvajs/dva/issues"
},
"scripts": {
"test": "cross-env NODE_ENV=test nyc mocha --no-timeouts",
"debug": "mocha --require babel-register --require ./test/setup.js --no-timeouts",
Expand Down Expand Up @@ -100,6 +106,10 @@
"router.js",
"fetch.js",
"mobile.js",
"index.js"
"index.js",
"index.d.ts",
"router.d.ts",
"fetch.d.ts",
"mobile.d.ts"
]
}
86 changes: 86 additions & 0 deletions router.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import Router from "react-router/lib/Router"
import Link from "react-router/lib/Link"
import IndexLink from "react-router/lib/IndexLink"
import IndexRedirect from "react-router/lib/IndexRedirect"
import IndexRoute from "react-router/lib/IndexRoute"
import Redirect from "react-router/lib/Redirect"
import Route from "react-router/lib/Route"
import History from "react-router/lib/History"
import Lifecycle from "react-router/lib/Lifecycle"
import RouteContext from "react-router/lib/RouteContext"
import browserHistory from "react-router/lib/browserHistory"
import hashHistory from "react-router/lib/hashHistory"
import useRoutes from "react-router/lib/useRoutes"
import { createRoutes } from "react-router/lib/RouteUtils"
import { formatPattern } from "react-router/lib/PatternUtils"
import RouterContext from "react-router/lib/RouterContext"
import PropTypes from "react-router/lib/PropTypes"
import match from "react-router/lib/match"
import useRouterHistory from "react-router/lib/useRouterHistory";
import createMemoryHistory from "react-router/lib/createMemoryHistory";
import withRouter from "react-router/lib/withRouter";
import applyRouterMiddleware from "react-router/lib/applyRouterMiddleware";

// PlainRoute is defined in the API documented at:
// https://github.com/rackt/react-router/blob/master/docs/API.md
// but not included in any of the .../lib modules above.
export type PlainRoute = ReactRouter.PlainRoute

// The following definitions are also very useful to export
// because by using these types lots of potential type errors
// can be exposed:
export type EnterHook = ReactRouter.EnterHook
export type LeaveHook = ReactRouter.LeaveHook
export type ParseQueryString = ReactRouter.ParseQueryString
export type RedirectFunction = ReactRouter.RedirectFunction
export type RouteComponentProps<P, R> = ReactRouter.RouteComponentProps<P, R>;
export type RouteHook = ReactRouter.RouteHook
export type StringifyQuery = ReactRouter.StringifyQuery
export type RouterListener = ReactRouter.RouterListener
export type RouterState = ReactRouter.RouterState
export type HistoryBase = ReactRouter.HistoryBase
export type RouterOnContext = ReactRouter.RouterOnContext
export type RouteProps = ReactRouter.RouteProps

interface routerRedux {
routerStateReducer: Function,
ReduxRouter: Function,
reduxReactRouter: Function,
isActive: Function,
historyAPI: Function,
push: Function,
replace: Function,
setState: Function,
go: Function,
goBack: Function,
goForward: Function,
}

export const routerRedux: routerRedux;

export {
Router,
Link,
IndexLink,
IndexRedirect,
IndexRoute,
Redirect,
Route,
History,
browserHistory,
hashHistory,
Lifecycle,
RouteContext,
useRoutes,
createRoutes,
formatPattern,
RouterContext,
PropTypes,
match,
useRouterHistory,
createMemoryHistory,
withRouter,
applyRouterMiddleware
};

export default Router;
Loading