Dmitriy Rudnik
Dmitriy Rudnik

Reputation: 59

What a correct type for array of interface with generic?

How to set correct type for routes array in this example to avoid error:

TS2314: Generic type 'Route ' requires 1 type argument(s).

code in TS playground

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

Answers (1)

Alexey Perestoronin
Alexey Perestoronin

Reputation: 166

Typescript Playground Link

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

Related Questions