Home > front end >  Automatically typed exports based on file structure in typescript
Automatically typed exports based on file structure in typescript

Time:10-31

I am wondering if is it possible to tell typescript that all files in specific folder must export specific typed value

For example I have folder models and every file in that folder must export object with type Model.

I can just use as keyword in each model file

import { Model } from 'types';

export default {
  ...
} as Model;

but is there a way to make typescript automatically type those files to get auto completion without need to importing Model type and asserting it?

export default {
  ...
}

It's not a big deal, I'm just curious if such a thing is possible, but I can't find anything about it.

CodePudding user response:

While you can define file export with

declare module '*.vue' {
  import type { DefineComponent } from 'vue'
  const component: DefineComponent<{}, {}, any>
  export default component
}

I doubt that would enforce the type of work on .ts files


I would recommend ensuring the correct export type by using a typechecking function

import {ensureModel} from '...'
export default ensureModel({
   modelId: 123
})
export function ensureModel<T extends Model>(v: T): T { return v }

optionally with

import {ensureModel} from '...'
export default ensureModel({
   modelId: 123 as const
}) // <-- export Model & {modelId: 123}
import {ensureModel} from '...'
export default ensureModel({
   modelId: 123
} as const) // <-- export Model & {modelId: 123, ...}

to freese constants

  • Related