如何区分打字稿中的模块名称和*主要导出类型*?

问题描述 投票:0回答:1

我想在 ts 中使用这样的代码:

//任务.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)

基本上我想将任务作为命名空间。但是类型任务正在干扰。

一个选项是:

//任务.ts

export type Task 

然后

//index.ts

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

另一种选择:

//任务.ts

export type Type 

//index.ts

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

你会如何处理这个问题?如何区分模块/命名空间任务和任务类型?

javascript typescript module namespaces node-modules
1个回答
0
投票

这是你想要的吗?你可以使用

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 module Task {
  export function increaseCost(task: Task, percent: number) {
    return { ...task, cost: task.cost * (1 + percent / 100) };
  }
}

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

© www.soinside.com 2019 - 2024. All rights reserved.