2017-08-05 70 views
1

我們正在將大型的React Javascript項目轉換爲TypeScript。如何避免React在導入JavaScript中定義的React類時在TypeScript中輸入錯誤?

我們已經定義現有文件陣營類:

// foo.js 
class Foo extends React.Component { ... } 

module.exports = Foo 

而且我們希望在我們的新打字稿文件中使用這些組件:

// bar.tsx 
import Foo from "./foo" 

export default class Bar extends React.Component<any, any> { 
    render() { return <Foo baz="buzz" /> } 
} 

然而,這導致了錯誤:

Property 'bar' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Foo> & Readonly<{ children?: ReactNode; }> & Read...'.

我們該如何避免錯誤?當我們修改文件時,我們會將文件轉換爲TypeScript,但如果我們必須修改原始文件包含的任何文件,這不是一個可行的策略。

回答

0

我們通過添加聲明文件untyped-components.d.ts來解決此問題。在這個文件中我們增加了一個聲明,對每個類型化成分:

declare module "foo" { 
    const Foo: any 
    export = Foo 
} 

... 

declare module "zap" { 
    const Zap: any 
    export = Zap 
} 

而現在當我們轉換一個文件,我們會從這個文件中刪除。