Commit b9638631 authored by Luis Fernando Alvarez D's avatar Luis Fernando Alvarez D Committed by Tim Neutkens

Prefer type over interface (#7164)

parent 5aba5e62
......@@ -3,18 +3,18 @@
import { ComponentType } from 'react';
import { parse } from 'url';
import mitt, {MittEmitter} from '../mitt';
import { formatWithValidation, getURL, loadGetInitialProps, IContext, IAppContext } from '../utils';
import { formatWithValidation, getURL, loadGetInitialProps, IContext, AppContextType } from '../utils';
import {rewriteUrlForNextExport} from './rewrite-url-for-export'
function toRoute(path: string): string {
return path.replace(/\/$/, '') || '/'
}
export interface IRouterInterface {
export type BaseRouter = {
route: string
pathname: string
query: string
asPath: string
asPath: string,
}
type RouteInfo = {
......@@ -28,7 +28,7 @@ type Subscription = (data: {App?: ComponentType} & RouteInfo) => void
type BeforePopStateCallback = (state: any) => boolean
export default class Router implements IRouterInterface {
export default class Router implements BaseRouter {
route: string
pathname: string
query: string
......@@ -460,7 +460,7 @@ export default class Router implements IRouterInterface {
this.componentLoadCancel = cancel
const { Component: App } = this.components['/_app']
const props = await loadGetInitialProps<IAppContext<Router>>(App, { Component, router: this, ctx })
const props = await loadGetInitialProps<AppContextType<Router>>(App, { Component, router: this, ctx })
if (cancel === this.componentLoadCancel) {
this.componentLoadCancel = null
......
......@@ -3,18 +3,18 @@ import { ServerResponse, IncomingMessage } from 'http';
import { ComponentType } from 'react'
import { ParsedUrlQuery } from 'querystring'
import { ManifestItem } from '../server/get-dynamic-import-bundles'
import { IRouterInterface } from './router/router'
import { BaseRouter } from './router/router'
/**
* Types used by both next and next-server
*/
export type NextComponentType<C extends IBaseContext = any, P = any, CP = {}> = ComponentType<CP> & {
export type NextComponentType<C extends BaseContext = any, P = any, CP = {}> = ComponentType<CP> & {
getInitialProps?(context: C): Promise<P>,
}
export type DocumentType = NextComponentType<IDocumentContext, IDocumentInitialProps, IDocumentProps>
export type DocumentType = NextComponentType<DocumentContext, DocumentInitialProps, DocumentProps>
export type AppType = NextComponentType<IAppContext, IAppInitialProps, IAppProps>
export type AppType = NextComponentType<AppContextType, AppInitialProps, AppPropsType>
export type Enhancer<C> = (Component: C) => C
......@@ -26,12 +26,12 @@ export type RenderPageResult = { html: string, head?: Array<JSX.Element | null>,
export type RenderPage = (options?: ComponentsEnhancer) => RenderPageResult | Promise<RenderPageResult>
export interface IBaseContext {
export type BaseContext = {
res?: ServerResponse
[k: string]: any
[k: string]: any,
}
export interface INEXTDATA {
export type INEXTDATA = {
dataManager: string
props: any
page: string
......@@ -42,7 +42,7 @@ export interface INEXTDATA {
runtimeConfig?: { [key: string]: any }
nextExport?: boolean
dynamicIds?: string[]
err?: Error & { statusCode?: number }
err?: Error & { statusCode?: number },
}
export interface IContext {
......@@ -54,30 +54,30 @@ export interface IContext {
asPath?: string
}
export interface IAppContext<R extends IRouterInterface = IRouterInterface> {
export type AppContextType<R extends BaseRouter = BaseRouter> = {
Component: NextComponentType<IContext>
router: R
ctx: IContext
ctx: IContext,
}
export interface IAppInitialProps {
pageProps: any
export type AppInitialProps = {
pageProps: any,
}
export interface IAppProps<R extends IRouterInterface = IRouterInterface> extends IAppInitialProps {
export type AppPropsType<R extends BaseRouter = BaseRouter> = AppInitialProps & {
Component: NextComponentType<IContext>
router: R
router: R,
}
export interface IDocumentContext extends IContext {
renderPage: RenderPage
export type DocumentContext = IContext & {
renderPage: RenderPage,
}
export interface IDocumentInitialProps extends RenderPageResult {
styles?: React.ReactElement[]
export type DocumentInitialProps = RenderPageResult & {
styles?: React.ReactElement[],
}
export interface IDocumentProps extends IDocumentInitialProps {
export type DocumentProps = DocumentInitialProps & {
__NEXT_DATA__: INEXTDATA
dangerousAsPath: string
ampPath: string
......@@ -87,7 +87,7 @@ export interface IDocumentProps extends IDocumentInitialProps {
devFiles: string[]
files: string[]
dynamicImports: ManifestItem[]
assetPrefix?: string
assetPrefix?: string,
}
/**
......@@ -123,7 +123,7 @@ export function isResSent(res: ServerResponse) {
return res.finished || res.headersSent
}
export async function loadGetInitialProps<C extends IBaseContext, P = any, CP = {}>(Component: NextComponentType<C, P, CP>, ctx: C): Promise<P | null> {
export async function loadGetInitialProps<C extends BaseContext, P = any, CP = {}>(Component: NextComponentType<C, P, CP>, ctx: C): Promise<P | null> {
if (process.env.NODE_ENV !== 'production') {
if (Component.prototype && Component.prototype.getInitialProps) {
const message = `"${getDisplayName(Component)}.getInitialProps()" is defined as an instance method - visit https://err.sh/zeit/next.js/get-initial-props-as-an-instance-method for more information.`
......
......@@ -2,9 +2,9 @@ import { IncomingMessage, ServerResponse } from 'http'
import { ParsedUrlQuery } from 'querystring'
import React from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import { IRouterInterface } from '../lib/router/router'
import { BaseRouter } from '../lib/router/router'
import mitt, { MittEmitter } from '../lib/mitt';
import { loadGetInitialProps, isResSent, getDisplayName, ComponentsEnhancer, RenderPage, IDocumentInitialProps, NextComponentType, DocumentType, AppType } from '../lib/utils'
import { loadGetInitialProps, isResSent, getDisplayName, ComponentsEnhancer, RenderPage, DocumentInitialProps, NextComponentType, DocumentType, AppType } from '../lib/utils'
import Head, { defaultHead } from '../lib/head'
// @ts-ignore types will be added later as it's an internal module
import Loadable from '../lib/loadable'
......@@ -28,7 +28,7 @@ function noRouter() {
throw new Error(message)
}
class ServerRouter implements IRouterInterface {
class ServerRouter implements BaseRouter {
route: string
pathname: string
query: string
......@@ -160,7 +160,7 @@ function renderDocument(
}: RenderOpts & {
dataManagerData: string,
props: any
docProps: IDocumentInitialProps
docProps: DocumentInitialProps
pathname: string
query: ParsedUrlQuery
dangerousAsPath: string
......
/* global window */
import React from 'react'
import Router, { IRouterInterface } from 'next-server/dist/lib/router/router'
import Router, { BaseRouter } from 'next-server/dist/lib/router/router'
import { RouterContext } from 'next-server/dist/lib/router-context'
import { RequestContext } from 'next-server/dist/lib/request-context'
......@@ -8,19 +8,19 @@ type ClassArguments<T> = T extends new(...args: infer U) => any ? U : any
type RouterArgs = ClassArguments<typeof Router>
interface ISingletonRouterBase {
type SingletonRouterBase = {
router: Router | null
readyCallbacks: Array<() => any>
ready(cb: () => any): void
ready(cb: () => any): void,
}
export interface IPublicRouterInstance extends IRouterInterface, Pick<Router, | 'components' | 'push' | 'replace' | 'reload' | 'back' | 'prefetch' | 'beforePopState'> {
events: typeof Router['events']
export type PublicRouterInstance = BaseRouter & Pick<Router, | 'components' | 'push' | 'replace' | 'reload' | 'back' | 'prefetch' | 'beforePopState'> & {
events: typeof Router['events'],
}
export interface ISingletonRouter extends ISingletonRouterBase, IPublicRouterInstance {}
export type SingletonRouter = SingletonRouterBase & PublicRouterInstance
const SingletonRouter: ISingletonRouterBase = {
const singletonRouter: SingletonRouterBase = {
router: null, // holds the actual router instance
readyCallbacks: [],
ready(cb: () => void) {
......@@ -31,16 +31,14 @@ const SingletonRouter: ISingletonRouterBase = {
},
}
// const x = SingletonRouter as IRealRouter
// Create public properties and methods of the router in the SingletonRouter
// Create public properties and methods of the router in the singletonRouter
const urlPropertyFields = ['pathname', 'route', 'query', 'asPath']
const propertyFields = ['components']
const routerEvents = ['routeChangeStart', 'beforeHistoryChange', 'routeChangeComplete', 'routeChangeError', 'hashChangeStart', 'hashChangeComplete']
const coreMethodFields = ['push', 'replace', 'reload', 'back', 'prefetch', 'beforePopState']
// Events is a static property on the router, the router doesn't have to be initialized to use it
Object.defineProperty(SingletonRouter, 'events', {
Object.defineProperty(singletonRouter, 'events', {
get() {
return Router.events
},
......@@ -51,7 +49,7 @@ propertyFields.concat(urlPropertyFields).forEach((field) => {
// the property assigned to the actual router
// The value might get changed as we change routes and this is the
// proper way to access it
Object.defineProperty(SingletonRouter, field, {
Object.defineProperty(singletonRouter, field, {
get() {
const router = getRouter() as any
return router[field] as string
......@@ -61,20 +59,20 @@ propertyFields.concat(urlPropertyFields).forEach((field) => {
coreMethodFields.forEach((field) => {
// We don't really know the types here, so we add them later instead
(SingletonRouter as any)[field] = (...args: any[]) => {
(singletonRouter as any)[field] = (...args: any[]) => {
const router = getRouter() as any
return router[field](...args)
}
})
routerEvents.forEach((event) => {
SingletonRouter.ready(() => {
singletonRouter.ready(() => {
Router.events.on(event, (...args) => {
const eventField = `on${event.charAt(0).toUpperCase()}${event.substring(1)}`
const singletonRouter = SingletonRouter as any
if (singletonRouter[eventField]) {
const _singletonRouter = singletonRouter as any
if (_singletonRouter[eventField]) {
try {
singletonRouter[eventField](...args)
_singletonRouter[eventField](...args)
} catch (err) {
// tslint:disable-next-line:no-console
console.error(`Error when running the Router event: ${eventField}`)
......@@ -87,16 +85,16 @@ routerEvents.forEach((event) => {
})
function getRouter() {
if (!SingletonRouter.router) {
if (!singletonRouter.router) {
const message = 'No router instance found.\n' +
'You should only use "next/router" inside the client side of your app.\n'
throw new Error(message)
}
return SingletonRouter.router
return singletonRouter.router
}
// Export the SingletonRouter and this is the public API.
export default SingletonRouter as ISingletonRouter
// Export the singletonRouter and this is the public API.
export default singletonRouter as SingletonRouter
// Reexport the withRoute HOC
export { default as withRouter } from './with-router'
......@@ -117,15 +115,15 @@ export function useRequest() {
// This is used in client side when we are initilizing the app.
// This should **not** use inside the server.
export const createRouter = (...args: RouterArgs) => {
SingletonRouter.router = new Router(...args)
SingletonRouter.readyCallbacks.forEach((cb) => cb())
SingletonRouter.readyCallbacks = []
singletonRouter.router = new Router(...args)
singletonRouter.readyCallbacks.forEach((cb) => cb())
singletonRouter.readyCallbacks = []
return SingletonRouter.router
return singletonRouter.router
}
// This function is used to create the `withRouter` router instance
export function makePublicRouterInstance(router: Router): IPublicRouterInstance {
export function makePublicRouterInstance(router: Router): PublicRouterInstance {
const _router = router as any
const instance = {} as any
......
import React from 'react'
import PropTypes from 'prop-types'
import { NextComponentType, IContext } from 'next-server/dist/lib/utils'
import { IPublicRouterInstance } from './router';
import { PublicRouterInstance } from './router';
export type WithRouterProps = {
router: IPublicRouterInstance,
router: PublicRouterInstance,
}
export type ExcludeRouterProps<P> = Pick<P, Exclude<keyof P, keyof WithRouterProps>>
......
import React, {ErrorInfo} from 'react'
import PropTypes from 'prop-types'
import { execOnce, loadGetInitialProps, NextComponentType, IContext, IAppContext, IAppInitialProps, IAppProps } from 'next-server/dist/lib/utils'
import { execOnce, loadGetInitialProps, NextComponentType, IContext, AppContextType, AppInitialProps, AppPropsType } from 'next-server/dist/lib/utils'
import { makePublicRouterInstance } from '../client/router'
export { NextComponentType, IContext, IAppContext, IAppInitialProps, IAppProps }
export { NextComponentType, IContext, AppInitialProps }
type Router = import('next-server/dist/lib/router/router').default
export type AppClientContext = IAppContext<Router>
export type AppContext = AppContextType<Router>
export type AppProps = IAppProps<Router>
export type AppProps = AppPropsType<Router>
export default class App extends React.Component<AppProps> {
static childContextTypes = {
router: PropTypes.object,
}
static async getInitialProps({ Component, ctx }: AppClientContext): Promise<IAppInitialProps> {
static async getInitialProps({ Component, ctx }: AppContext): Promise<AppInitialProps> {
const pageProps = await loadGetInitialProps(Component, ctx)
return { pageProps }
}
......
......@@ -2,7 +2,7 @@
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import { cleanAmpPath } from 'next-server/dist/server/utils'
import { IDocumentContext, IDocumentInitialProps, IDocumentProps } from 'next-server/dist/lib/utils'
import { DocumentContext, DocumentInitialProps, DocumentProps } from 'next-server/dist/lib/utils'
import { htmlEscapeJsonString } from '../server/htmlescape'
import flush from 'styled-jsx/server'
import {
......@@ -10,33 +10,33 @@ import {
CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
} from 'next-server/constants'
export { IDocumentContext, IDocumentInitialProps, IDocumentProps }
export { DocumentContext, DocumentInitialProps, DocumentProps }
export interface IOriginProps {
export type OriginProps = {
nonce?: string
crossOrigin?: string
crossOrigin?: string,
}
export interface IDocumentComponentContext {
readonly _documentProps: IDocumentProps
readonly _devOnlyInvalidateCacheQueryString: string
export type DocumentComponentContext = {
readonly _documentProps: DocumentProps
readonly _devOnlyInvalidateCacheQueryString: string,
}
export default class Document extends Component<IDocumentProps> {
export default class Document extends Component<DocumentProps> {
static childContextTypes = {
_documentProps: PropTypes.any,
_devOnlyInvalidateCacheQueryString: PropTypes.string,
}
static async getInitialProps({ renderPage }: IDocumentContext): Promise<IDocumentInitialProps> {
static async getInitialProps({ renderPage }: DocumentContext): Promise<DocumentInitialProps> {
const { html, head, dataOnly } = await renderPage()
const styles = flush()
return { html, head, styles, dataOnly }
}
context!: IDocumentComponentContext
context!: DocumentComponentContext
getChildContext(): IDocumentComponentContext {
getChildContext(): DocumentComponentContext {
return {
_documentProps: this.props,
// In dev we invalidate the cache by appending a timestamp to the resource URL.
......@@ -69,7 +69,7 @@ export class Html extends Component {
children: PropTypes.node.isRequired,
}
context!: IDocumentComponentContext
context!: DocumentComponentContext
render() {
const { amphtml } = this.context._documentProps
......@@ -79,7 +79,7 @@ export class Html extends Component {
}
}
export class Head extends Component<IOriginProps> {
export class Head extends Component<OriginProps> {
static contextTypes = {
_documentProps: PropTypes.any,
_devOnlyInvalidateCacheQueryString: PropTypes.string,
......@@ -90,7 +90,7 @@ export class Head extends Component<IOriginProps> {
crossOrigin: PropTypes.string,
}
context!: IDocumentComponentContext
context!: DocumentComponentContext
getCssLinks() {
const { assetPrefix, files } = this.context._documentProps
......@@ -343,7 +343,7 @@ export class Main extends Component {
_devOnlyInvalidateCacheQueryString: PropTypes.string,
}
context!: IDocumentComponentContext
context!: DocumentComponentContext
render() {
const { amphtml, html } = this.context._documentProps
......@@ -352,7 +352,7 @@ export class Main extends Component {
}
}
export class NextScript extends Component<IOriginProps> {
export class NextScript extends Component<OriginProps> {
static contextTypes = {
_documentProps: PropTypes.any,
_devOnlyInvalidateCacheQueryString: PropTypes.string,
......@@ -363,7 +363,7 @@ export class NextScript extends Component<IOriginProps> {
crossOrigin: PropTypes.string,
}
context!: IDocumentComponentContext
context!: DocumentComponentContext
getDynamicChunks() {
const { dynamicImports, assetPrefix } = this.context._documentProps
......@@ -409,7 +409,7 @@ export class NextScript extends Component<IOriginProps> {
})
}
static getInlineScriptSource(documentProps: IDocumentProps) {
static getInlineScriptSource(documentProps: DocumentProps) {
const { __NEXT_DATA__ } = documentProps
try {
const data = JSON.stringify(__NEXT_DATA__)
......
......@@ -9,11 +9,11 @@ const statusCodes: { [code: number]: string } = {
501: 'Not Implemented',
}
export interface IErrorProps {
statusCode: number
export type ErrorProps = {
statusCode: number,
}
export default class Error<P = {}> extends React.Component<P & IErrorProps> {
export default class Error<P = {}> extends React.Component<P & ErrorProps> {
static displayName = 'ErrorPage'
static getInitialProps({ res, err }: IContext) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment