使用 tslint 强制不变性
Using tslint to enforce immutability
作为 React 开发新手,我刚刚意识到我一直在不经意间直接改变 state 和 props。
有很多例子:
const {variable} = this.props;
variable[index] = value;
// do something local with var - not realizing that variable is changed
我的代码库中有数百个这样的实例。
是否有 tslint 规则或方法可以找到每个实例,其中我已经改变了 props 或 state 应该是只读的。
我知道那里有一个 tslint 规则
TS2540: Cannot assign to ‘url’ because it is a constant or a read-only property.
但我不知道如何打开它。据我了解,在 React Typescript 中,props 和 state 被包装在 Readonly<> 中,每当我尝试改变 props 或 state 时,它应该会触发这个错误。
您可以在创建接口时将它们声明为 readonly
,并将 ReadonlyArray
用于数组、道具和状态,例如:
interface ButtonProps {
readonly onChange: (event: ChangeEvent) => void;
readonly classes: ReadonlyArray<string>;
}
class Button extends React.Component<ButtonProps> { ... }
那样的话,只要所有成员都是 readonly
,你就应该在任何地方都进行检查,并且是 typescript 编译器会出错,而不是 tslint。
您可以做的一件事是使用 tslint-immutable 中的规则来确保您不会错过任何 readonly
接口和数组
作为 React 开发新手,我刚刚意识到我一直在不经意间直接改变 state 和 props。
有很多例子:
const {variable} = this.props;
variable[index] = value;
// do something local with var - not realizing that variable is changed
我的代码库中有数百个这样的实例。
是否有 tslint 规则或方法可以找到每个实例,其中我已经改变了 props 或 state 应该是只读的。
我知道那里有一个 tslint 规则
TS2540: Cannot assign to ‘url’ because it is a constant or a read-only property.
但我不知道如何打开它。据我了解,在 React Typescript 中,props 和 state 被包装在 Readonly<> 中,每当我尝试改变 props 或 state 时,它应该会触发这个错误。
您可以在创建接口时将它们声明为 readonly
,并将 ReadonlyArray
用于数组、道具和状态,例如:
interface ButtonProps {
readonly onChange: (event: ChangeEvent) => void;
readonly classes: ReadonlyArray<string>;
}
class Button extends React.Component<ButtonProps> { ... }
那样的话,只要所有成员都是 readonly
,你就应该在任何地方都进行检查,并且是 typescript 编译器会出错,而不是 tslint。
您可以做的一件事是使用 tslint-immutable 中的规则来确保您不会错过任何 readonly
接口和数组