javascript 如何区分模块名和typescript中的 *main exported type*?

unguejic  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(78)

我想在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)

基本上我想做任务作为一个命名空间。但type任务正在干扰。
一种选择是:
// task.ts

export type Task

然后
//index.ts

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

另一种选择:
// task.ts

export type Type

//index.ts

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

你会怎么做?如何区分模块/命名空间Task和Task类型?

k2arahey

k2arahey1#

您可以使用modulenamespace关键字,但不再推荐使用module

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) };
  }
}

一个在线演示在这里stackblitz type。(打开控制台查看结果。)

相关问题