Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import * as iterable array in TypeScript

Tags:

typescript

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
like image 972
Livio Brunner Avatar asked Mar 06 '18 16:03

Livio Brunner


People also ask

How do I import files into TypeScript?

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 .

How do you define an array of objects in TypeScript?

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!

Does TypeScript use import?

Importing TypesWith TypeScript 3.8, you can import a type using the import statement, or using import type .

What is import type in TypeScript?

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.


1 Answers

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.

like image 128
Tao Avatar answered Sep 18 '22 11:09

Tao