0

How can I type the this argument when my function receives it?

import { generatePath } from 'react-router-dom';

type generatePathParamsType = Parameters<typeof generatePath>[1];

// Following type definition of 'this' is not working
const generatePathFactory = function (this: typeof ENV_DASHBOARD) {
  return function (args: generatePathParamsType = {}) {
    // 'this' implicitly has type 'any' because it does not have a type annotation.
    return generatePath(this.PATH, args);
  };
};

const ENV_DASHBOARD = {
  PATH: "/dashboard/:environmentId",
  generatePath: generatePathFactory.apply(this),
  TITLE: "Dashboard"
};

console.log(ENV_DASHBOARD.generatePath({ environmentId: "1" })); // '/dashboard/1'

Demo at codesandbox

Rashomon
  • 5,962
  • 4
  • 29
  • 67
  • 1
    Does this answer your question? [Self-references in object literals / initializers](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers) – Ivar Jun 15 '22 at 08:56
  • In `generatePath: generatePathFactory.apply(this),`, `this` does _not_ refer to `ENV_DASHBOARD`... – Cerbrus Jun 15 '22 at 08:57
  • @Ivar the question is about self reference in objects, no typing the `this` argument – Rashomon Jun 15 '22 at 09:02
  • I don't really see why the answers to the linked question don't apply here. Both questions are referencing `this` in an array literal, the `this` means the same in both question, regardless of whether you use it as an argument or not. You can't directly reference the object literal itself the way you want it. The answers to the proposed duplicates apply. (T.J. Crowder's and Felix Kling's answers are most likely your best options if you don't want to repeat the call every time you access `generatePath`.) – Ivar Jun 15 '22 at 09:06

0 Answers0