Home > Software design >  Svelte / Typescript - sharing a namespace across multiple files
Svelte / Typescript - sharing a namespace across multiple files

Time:01-03

I'm not sure if it's possible, but before I rule it out, I just wanted some feedback.

I am organising the variable types in my Svelte/Typescript project under namespaces. I would ideally like all types from multiple files organised under a single namespace (Types)

For example: - /types/type.user.ts

export namespace Types {
  export type User {
   name : '',
   email: ''
  }
}

And then in -components/type.column.ts

export namespace Types {
  export type Column {
   id : '',
   filter : ''
  }
}

The problem arises when importing these type into a single file as it causes an ambiguity in resolving the export namespace:

import { Type } from "/src/types/type.user";
import { Type } from "/src/components/types/type.column";

I can't see a way to work around this. Is this possible before I resign myself to giving up on namespaces or merging types into a single file?

CodePudding user response:

To get this to work I created 3 files: src/components/type.column.ts, src/types/type.user.ts and component.svelte.

I also had to modify the tsconfig.json file by setting "isoluatedModules": false (as that is apparently the default for svelte projects created with Vite).

src/components/type.column.ts

namespace Types {
  export type Column = {
    id: string;
    filter: string;
  }
}

src/types/type.user.ts

/// <reference path="../components/type.column.ts" />
namespace Types {
  export type User = { 
    name: string;
    email: string;
  }
}

component.svelte

<script lang="ts">
/// <reference path="../types/type.user.ts">
const someUser: Types.User = {
  email: '',
  name: ''
};

const someColumn: Types.Column = {
  filter: '',
  id: 'some-id'
};

</script>

I will note, however, that I'm not sure I would personally use this method. I tend to try and keep things in the most related location, so I would likely just remove the Types namespace, and simply export the singular type from each file. I don't see an issue with doing something like:

<script lang="ts">
import type { User } from '../types/type.user';
import type { Column } from '../components/type.column';
const someuser: User = {...};
const someColumn: Column = {...};
</script>

This largely boils down to personal preference, but by changing the isolatedModules setting it's possible we would run into errors with svelte preprocessor later down the line -- I'll be forward in saying I don't actually know a lot about the svelte team's reasoning for using this setting so I can't speak too much more about it, but I figure they must have put it there for a reason. Just keep in mind that while this works, it may end up being the cause of some frustrations in the future.

  • Related