Search code examples
javascripttypescriptmodulenamespacesnode-modules

How do i differentiate module name from *main exported type* in typescript?


i would like to use my code like this in ts:

// task.ts

export type Task = {
  name: string
  description: string
  cost: number
  done: boolean
}


export function increaseCost(task: Task, percent: number) {
  return { ...task, cost: task.cost * (1 + percent / 100) }
}

// index.ts

import {Task,  increaseCost} from "./task.ts"
 
let task: Task = {...}

Task.increaseCost(task, 15)
Task.anotherFunction(task)
Task.yetAnotherFunction(task)

Basically i would like to do Task as a namespace. But type Task is interfering.

An option would be:

// task.ts

export type Task 

and then

// index.ts

import * as Task from "task.ts"
let task: Task.Task // this seems redundant

Another option:

// task.ts

export type Type 

// index.ts

import * as Task from "task.ts" 
let task: Task.Type // seems odd/weird  

How would you approach this? How would you differentiate module/namespace Task from Task type?


Solution

  • You can use the module or namespace keywords, although module is not recommended anymore:

    import { Task } from './task';
    let a: Task = { cost: 10, description: '', done: false, name: '' };
    console.log(Task.increaseCost(a, 10));
    
    // task.ts
    export type Task = {
      name: string;
      description: string;
      cost: number;
      done: boolean;
    };
    
    export namespace Task {
      export function increaseCost(task: Task, percent: number) {
        return { ...task, cost: task.cost * (1 + percent / 100) };
      }
    }
    
    

    A online demo is at here stackblitz type. (Open the console to see the result.)