定義時使用的反應打字稿組件,我們可以寫類似:如何使用打字稿jsdoc註解陣營PropTypes
class SomeComponent extends React.Component<PropInterface, StateInterface> {
// ...
}
有沒有辦法做相當於使用jsdoc annotations,並有道具類型檢查。
定義時使用的反應打字稿組件,我們可以寫類似:如何使用打字稿jsdoc註解陣營PropTypes
class SomeComponent extends React.Component<PropInterface, StateInterface> {
// ...
}
有沒有辦法做相當於使用jsdoc annotations,並有道具類型檢查。
雖然它可能不那麼好,但它可以工作。
// 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
感謝您的回答。這工作。你還可以建議如何標記傳遞未指定的道具作爲錯誤嗎? 例如。在你的例子中,如果我調用類似於:'
嗯,這很奇怪。當我用''compilerOptions'調用'
我正在嘗試將所有文件作爲js文件(包括導入它的文件)以及'// @ ts-check'。 tsconfig: ' { 「compilerOptions」:{ \t 「noEmit」:真實, \t 「allowJs」:真實, 「JSX」: 「響應」, 「checkJs」:真實, 「allowJs」 :真 }, 「包括」: \t 「./src/」 ] } ' – lorefnon
萬一有人正在尋找替代解決方案。 關於這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;
運行時'PropTypes'檢查與靜態'打字稿'檢查混合在一起。我會放棄'PropTypes',因爲兩者都沒有意義。 – Artin
我更喜歡下面的表格(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>
);
}
}
您用過陣營的內置'PropTypes'? – Li357
@AluanHaddad Typescript最近通過jsdoc註釋添加了類型檢查支持。請參閱問題中的鏈接。 – lorefnon
@AndrewLi這已被棄用。而且我希望檢查在編譯時發生。 – lorefnon