How can I access multiple classes in different files, as array, using TypeScript?
folder structure:
├── index.ts
└── models
├── index.ts
├── image.entity.ts
└── user.entity.ts
image.entity.ts:
export class Image { }
user.entity.ts:
export class User { }
models/index.ts:
export * from './image.entity';
export * from './user.entity';
index.ts (desired output):
import * as models from './models/index';
// Is an iterable array, instead of a "module"
console.log(models.length) // 2
To import a class from another file in TypeScript: Export the class from file A , e.g. export class Employee {} . Import the class in file B as import { Employee } from './another-file' . Use the class in file B .
To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!
Importing TypesWith TypeScript 3.8, you can import a type using the import statement, or using import type .
import type only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there's no remnant of it at runtime. Similarly, export type only provides an export that can be used for type contexts, and is also erased from TypeScript's output.
As you have it, you could iterate over models
simply with one of Object.keys
, Object.values
or Object.entries
. Note that you'll need to add es2017
to --lib
for the latter two to work.
If you really want models
to be an array you could do it like this:
image.entity.ts
export default class Image { }
user.entity.ts
export default class User { }
index.ts
import Image from './image.entity';
import User from './user.entity';
export default [
Image,
User,
]
and then import it like this:
import models from './models';
console.log(models.length) // 2
Note that you don't need to use deault imports/exports but they will save you some * as x
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With