我希望开发人员使用类/接口而不是直接导入函数。
有没有办法限制只有类才能导入函数?
我不想将所有功能放在一个文件中,因为它在大型项目中不可扩展
即我不想使用这种模式:
// myclass.ts
// no exports on the functions
function foo(){ ... }
function bar(){ ... }
export class MyClass {
Foo(){ return foo() }
Bar(){ return bar() }
}
我想要实现的目标:
// foo.ts
export function foo(){ ... }
// I want this to be private but it needs to be exported so the class below can use it
// bar.ts
export function bar() { ... }
// myclass.ts
import { foo } from 'foo';
import { bar } from 'bar';
export class MyClass {
Foo(){ return foo() }
Bar(){ return bar() }
}
// anyotherfile.ts
import { foo } from 'foo' // Stop from importing directly
import { MyClass } from 'myclass' // use this instead
您可以通过几种方式轻松实现这一目标。主要是通过封装或显式导出。
示例1:
const foo = () => {
console.log('do something');
return 'something'
}
const bar = () => {
console.log("do something else");
return "something else";
};
export const MyClass = () => {
const fooResult = foo();
const barResult = bar();
return {fooResult, barResult}
}
//to use
import MyClass from 'myClass/location';
export const Example = () => {
console.log(MyClass().fooResult);
const {barResult} = MyClass();
console.log(barResult);
}
示例2:
export const MyClass = () => {
const foo = () => {
console.log("do something");
return "something";
};
const bar = () => {
console.log("do something else");
return "something else";
};
return { foo, bar };
};
//to use:
import MyClass from './location';
export const Example = ()=>{
const {foo, bar} = MyClass();
console.log(foo, bar);
}