#How to invoke a method of a class from Record<>

10 messages · Page 1 of 1 (latest)

rustic dragon
#

Hi all, I have a code below

class C1{
  load1(){}
}

class C2{
  load2(){}
}
class C3{
  load3(){}
}

type clsName = typeof C1 | typeof C2;
const mapper: Record<"c1" | "c2", clsName> = {
  "c1": C1,
  "c2": C2,
}

When calling new mapper["c1"]().load1() => there is error, how could I invoke a method of a class depending on the input of the Record type

bold bough
#

use satisfies instead of a type annotation so the exact shape doesn't get lost

burnt oracleBOT
#
that_guy977#0

Preview:```ts
...
type ClsName = typeof C1 | typeof C2;
const mapper = {
"c1": C1,
"c2": C2,
} satisfies Record<"c1" | "c2", ClsName>

new mapper.c1().load1()```

rustic dragon
#

@bold bough
Are there any advantages if not using satisfies as below

const mapper2 = {
  "c1": C1,
  "c2": C2
}
new mapper2.c1().load1()
undone swallow
#

If you don't care about verifying mapper to be a certain shape, then you don't need satisfies.

rustic dragon
#

@undone swallow , @bold bough
I have observed an issue that is if I wrap the mapper inside a function

type ClsName = typeof C1 | typeof C2;
const mapper = {
  "c1": new C1(),
  "c2": new C2(),
} satisfies Record<"c1" | "c2", InstanceType<ClsName>>


function createService(name: "c1" | "c2"){
  return mapper[name]
}

// Error in here

const service1 = createService("c1").load1()
//Property 'load1' does not exist on type 'C1 | C2'.
//  Property 'load1' does not exist on type 'C2'.
burnt oracleBOT
#
nonspicyburrito#0

Preview:```ts
class C1 {
load1() {}
}

class C2 {
load2() {}
}

const mapper = {
c1: new C1(),
c2: new C2(),
}
type Mapper = typeof mapper

function createService<T extends keyof Mapper>(
name: T
) {
return mapper[name]
}

const service1 = createService("c1").load1()
...```

rustic dragon
#

Thanks @undone swallow , would you help point out why the createService() in my code doesn't return the correct instance class ?

undone swallow
#

Because it's not generic.