#Can I set the type of `obj.function`'s `this` to be `obj`'s properties?

23 messages · Page 1 of 1 (latest)

wooden beaconBOT
#
bawdyinkslinger#0

Preview:```ts
declare namespace NodeJS {
type Timeout = any
}
let _macros: {[index: string]: any} = {}

function macrosAdd(
name: string[] | string,
def: any /* Actually, a set of optional and required properties. timers is optional */
) {
if (Array.isArray(name)) {
name.forEach(name
...```

brisk jewel
#

I think the code example is easier to understand than my title

#

!pg

#

!ts

wooden beaconBOT
#
declare namespace NodeJS {
  type Timeout = any;
}
let _macros: { [index: string]: any } = {};

function macrosAdd(name: string[] | string, def: any /* Actually, a set of optional and required properties. `timers` is optional */) {
  if (Array.isArray(name)) {
    name.forEach((name) => macrosAdd(name, def));
    return;
  }
  // ...

  if (typeof def === "object") {
    _macros[name] = Object.assign(Object.create(null), def, {
      _MACRO_API: true,
    });
  }

  // ...
}

macrosAdd("timed", {
  isAsync: true,
  tags: ["next"],
  timers: new Set<NodeJS.Timeout>(),
  t8nRe: /^(?:transition|t8n)$/,

  handler(
/**
 * QUESTION: can I set the type of `handler`'s `this` to all the properties of its containing object?
 * 
 * e.g., in this call `this` would be: 
 * 
 *     this: { isAsync: boolean, tags: string[], timers: Set<NodeJS.Timeout>, t8nRe }
 * 
 *  */    
  ) {
    // ...

    const timers = this.timers; // I want this to be `Set<NodeJS.Timeout>`, not `any` or `Set<NodeJS.Timeout> | undefined`
//        ^? - const timers: any
  },
});
civic ore
#

Change it into:

function macrosAdd<T>(name: string[] | string, def: T) {}
brisk jewel
#

I'm getting better at this because I've did that next

#

That's better, but it handler still doesn't know the shape of its this

#

oh wait...

#

that did fix it in my example

#

wonder why that didn't fix it in my actual code. Let me try to find the difference

#

actually that didn't completely work for the example code either:

wooden beaconBOT
#
bawdyinkslinger#0

Preview:```ts
declare namespace NodeJS {
type Timeout = any
}
let _macros: {[index: string]: any} = {}

function macrosAdd<DEF>(
name: string[] | string,
def: DEF /* Actually, a set of optional and required properties. timers is optional */
) {
if (Array.isArray(name)) {
name.forEach(name
...```

civic ore
#

It works, doesn't it?

#

All the this properties are there.

brisk jewel
#

oh wait

#

that's cause of my declaration I guess

#

doh

civic ore
#

Btw, for playground you can do import 'node' to bring in Node types.

brisk jewel
#

ooh, thank you

#

I can't figure out what the differences between this example and my real code. Oh well