Reputation: 59
How to set correct type for routes array in this example to avoid error:
TS2314: Generic type 'Route ' requires 1 type argument(s).
interface Route<T> {
path: string
handler: () => T
}
class Router {
routes: Route[] = []
addRoute<T>(path: string, handler: Route<T>['handler']) {
this.routes.push({
path,
handler
})
}
}
const router = new Router()
router.addRoute<string>('home', () => '123')
Upvotes: 0
Views: 61
Reputation: 166
interface Route<T> {
path: string
handler: () => T
}
class Router {
routes: Route<unknown>[] = []
addRoute<T>(path: string, handler: Route<T>['handler']) {
this.routes.push({
path,
handler
})
}
}
const router = new Router()
router.addRoute('foo', () => '123')
router.addRoute('bar', () => 123)
// or
class Router2<T> {
routes: Route<T>[] = []
addRoute(path: string, handler: Route<T>['handler']) {
this.routes.push({
path,
handler
})
}
}
const router2Str = new Router2<string>()
router2Str.addRoute('baz', () => '123')
const router2Num = new Router2<number>()
router2Num.addRoute('quiz', () => 123)
Upvotes: 1