Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

typescript - How to structure utility class

I have several utility functions. What is the best way to package these up, and then import them?

This is what I am trying to do:

import * as util from './util'

export class myClass{
     constructor()
     {
           util.doSomething("test");
     }
}

Then in the class:

export class Util{
    doSomething(val: string){ return val;}

    doSomethingElse(val: string{ return val;}
}

The error message I get from VS is:

Property doSomething does not exist on type util.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you create a file utils.ts which contains

export default class Utils {
    static doSomething(val: string) { return val; }
    static doSomethingElse(val: string) { return val; }
}

then you can simplify your client code like this:

import Utils from './utils'

export class MyClass {
     constructor()
     {
         Utils.doSomething("test");
     }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...