How can I make old style classes work in typescript?

前端 未结 3 840
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-11 20:04

While converting a large number of files to typescript, I have many classes declared this way.

function FooClass() {
    this.bar = 1; // error TS2683: \'thi         


        
3条回答
  •  甜味超标
    2020-12-11 20:31

    If you don't want to convert them, I'd suggest to keep them as JavaScript files and just write declaration files for them. Then TypeScript would recognise them implicitly, without rewriting the code.

    You could add to your project a types.d.ts file and:

    declare class FooClass {
        public bar: number;
        public myMethod: () => void;
        ...
    }
    

    With such a file in your project, TypeScript will allow you to do const myClass = new FooClass();.

    Of course, you still have to add your JavaScript code (or you'll run into runtime errors), importing it the way that suits you. If you were using global files, by loading them in your page, or in whichever environment you're working on. If your old code was in modules, you import those modules when you need to use them.

提交回复
热议问题