0

I have a folder full of json schemas, written in typescript.

I'd like to be able to import them all and keep the typing without having 30 import statements.

I'm using these for validating json sent to my API with Ajv. I want my API mount points to be the same as the naming convention used for my schemas.

/users -> schemas/users.schema.ts
/account/stats -> schemas/account/stats.schema.ts

I have a string array of available mount points and would love to be able to do

API.Mount("account/stats")

so basically

import `/schemas/${mount}.schema.ts` <-- import all these guys
softgrip
  • 53
  • 4

1 Answers1

1

I don't think there is a way to import with wildcards in only Typescript, nor do they want to.

I think your best option is to create an index.ts file in the /schemas folder:

export { default as Stats } from './stats.schema.ts';
export { default as Users } from './users.schema.ts';
export { Items } from './items.schema.ts'; // When it's not a default export

Then in your file where you want to use one you just say

import { Items, Users } from '/schemas'

This post may help understanding index.ts files.

Diesel
  • 5,099
  • 7
  • 43
  • 81
  • Thanks for the reply. I may well make an index.ts file. I only need to mount all the schemas in a single route creation file. It still looks like the bunch of imports is going to exist somewhere. At least the index.ts file would make it centralized if I need to use it some place else. I'll probably go this route. No pun intended :) – softgrip Sep 08 '20 at 06:44
  • Yah it allows your imports in your main files to be nice and clean, and your exports in your index.ts to be explicit. Without the index.ts, each file would have a line for each import in a different file. With the index.ts, you only have one line from the folder itself from one "file" – Diesel Sep 09 '20 at 03:56