2017-05-03 63 views
2

定義時使用的反應打字稿組件,我們可以寫類似:如何使用打字稿jsdoc註解陣營PropTypes

class SomeComponent extends React.Component<PropInterface, StateInterface> { 
    // ... 
} 

有沒有辦法做相當於使用jsdoc annotations,並有道具類型檢查。

+0

您用過陣營的內置'PropTypes'? – Li357

+0

@AluanHaddad Typescript最近通過jsdoc註釋添加了類型檢查支持。請參閱問題中的鏈接。 – lorefnon

+0

@AndrewLi這已被棄用。而且我希望檢查在編譯時發生。 – lorefnon

回答

3

雖然它可能不那麼好,但它可以工作。

// Foo.jsx 
import * as React from 'react'; 

/** 
* @type {{ new(props: any): { 
    props: { a: string, b: number }, 
    state: any, 
    context: any, 
    refs: any, 
    render: any, 
    setState: any, 
    forceUpdate: any 
    } }} 
*/ 
const Foo = class Foo extends React.Component { 
    render() { 
    return <div className={this.props.a}>{this.props.b}</div>; 
    } 
}; 
export default Foo; 

// import Foo and use it in .tsx or .jsx file 
import Foo from './Foo'; 

<Foo/>; // error: Type '{}' is not assignable to type '{ a: string; b: number; }' 
<Foo a='a' b={0}/>; // OK 
+0

感謝您的回答。這工作。你還可以建議如何標記傳遞未指定的道具作爲錯誤嗎? 例如。在你的例子中,如果我調用類似於:'',我不會收到任何錯誤。 – lorefnon

+0

嗯,這很奇怪。當我用''compilerOptions'調用''時,我得到一個錯誤'Property'c'不存在於'IntrinsicAttributes ...'類型中: {「target」:「es5」,「allowJs」:true,「checkJs」:true,「jsx」:「react」}'。我正在使用TypeScript 2.3.2。 – kimamula

+0

我正在嘗試將所有文​​件作爲js文件(包括導入它的文件)以及'// @ ts-check'。 tsconfig: ' { 「compilerOptions」:{ \t 「noEmit」:真實, \t 「allowJs」:真實, 「JSX」: 「響應」, 「checkJs」:真實, 「allowJs」 :真 }, 「包括」: \t 「./src/」 ] } ' – lorefnon

0

萬一有人正在尋找替代解決方案。 關於這Typescript issue你也可以這樣做。

import React, { Component } from 'react'; 
import PropTypes from 'prop-types'; 

/** 
* @augments {Component<{onSubmit:function, text:string}>} 
* @param {object} event - Input event 
* @return {React.ReactElement} - React component 
*/ 
class Test extends Component { 
    handleInput = (event) => { 
    event.preventDefault(); 
    this.props.onSubmit(event.target.value); 
    }; 

    render() { 
    const { text } = this.props; 
    return <div>Hello, property :O {text}</div>; 
    } 
} 

Test.propTypes = { 
    onSubmit: PropTypes.func.isRequired, 
    text: PropTypes.string.isRequired, 
}; 

export default Test; 
+0

運行時'PropTypes'檢查與靜態'打字稿'檢查混合在一起。我會放棄'PropTypes',因爲兩者都沒有意義。 – Artin

2

我更喜歡下面的表格(ES2015 + @types/react):

/** 
* @typedef {object} Props 
* @prop {string} className 
* @prop {number} numberProp 
* 
* @extends {Component<Props>} 
*/ 
export default class SomeComponent extends Component { 
    render() { 
     return (
      <div className={this.props.className}> 
       {this.props.numberProp} 
      </div> 
     ); 
    } 

}