kriasoft / universal-router

A simple middleware-style router for isomorphic JavaScript web apps
https://www.kriasoft.com/universal-router/
MIT License
1.7k stars 105 forks source link

overriding Route type when initializing UniversalRouter #185

Open webican opened 4 years ago

webican commented 4 years ago

I'm submitting a ...

I'm having trouble overriding Route type when initializing UniversalRouter:

interface MyRouteType {
  customProperty: any;
}

const router = new UniversalRouter<MyContextType, MyRouteType>(routes, {
  async resolveRoute(context, params) {
    if (context.route.customProperty) {
       console.log(context.route.customProperty);
    }
  },
});

My IDE is complaining that customProperty doesn't exist on context.route

I fixed it like this: http://www.mergely.com/oC2xyDZh/, but I'm still new to typescript and I'm not sure if my fix is any good.

frenzzy commented 4 years ago

@jazblueful, hi! Currently the router does not accept a route type. The second type variable is route result but not route.

- new UniversalRouter<Context, Route>(routes, options)
+ new UniversalRouter<Context, Result>(routes, options)

so, the only way to extend Route type is to add an extended interface in your code and typescript will merge them.

import { Route } from 'universal-router'

interface Route {
  customProperty: any;
}

// ...

I want to allow to redefine Route type in the next router version, see todo in #183

webican commented 4 years ago

hi @frenzzy, Thanks for a quick reply and clarification. It makes sense regarding the Result type.

However when I try to extend Route type this way I get: "TS2440: Import declaration conflicts with local declaration of 'Route'."

webican commented 4 years ago

It looks like merging imported and local interfaces was removed in TS 3.7 https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-rc/#local-and-imported-type-declarations-now-conflict and only option for me is to wait for the next router version.

frenzzy commented 4 years ago

Have you tried to add a universal-router.d.ts in your project source root with the following content?

declare module 'universal-router' {
  export interface Route {
    customProperty: any;
  }
}

Just found an article: TypeScript: Adding Custom Type Definitions for Existing Libraries

Also I will try to find time next week to update PR #183 and release v9, but it is not guaranteed 🤷‍♂️

webican commented 4 years ago

Awesome! thank you @frenzzy :)