Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference instance of factory created class in Typescript? Cannot find name error

Tags:

typescript

Typescript is failing to reference factory created class. Here's an example code:

// factory.ts
export const createClass = () =>
  class Model {
    // ...
  }

// ModelA.ts
import {createClass} from './factory';

export const ModelA = createClass();

let a: ModelA; // Cannot find name 'ModelA';

// other.ts
import {ModelA} from './ModelA';
new ModelA() // Cannot find name 'ModelA';

What am I doing wrong here?

like image 931
Joon Avatar asked Nov 24 '25 11:11

Joon


1 Answers

If you are trying to get the insurance type for the class generated by the function then you can use the InstanceType conditional type.

export const createClass = () =>
class Model {
    // ...
}


export const ModelA = createClass();
type ModelA = InstanceType<typeof ModelA>
let a: ModelA = new ModelA(); // ok
like image 117
Titian Cernicova-Dragomir Avatar answered Nov 27 '25 15:11

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!