TypeScript 部分接口对象 [英] TypeScript partial interface object
问题描述
在 React 中,组件定义看起来像这样:
In React, the Component definition looks something like this:
class Component<S> {
state:S;
setState(state:S):void;
}
然后你定义一个这样的组件:
And you define a component like this:
interface MyState {
name: string;
age: number;
}
class MyComponent extends Component<MyState> { }
现在我遇到的问题是,在 React API 中 setState
应该使用 partial 状态对象调用,表示要更新的属性,如下所示:
Now the issue I have is that in the React API setState
is supposed to be called with a partial state object, representing properties to be updated, like this:
setState({name: "Aaron"});
注意 age
没有声明.我遇到的问题是 TypeScript 不允许这样做,它给出了一个分配错误,例如 Property 'age' is missing
.根据我的理解,react.d.ts
定义在这个意义上是错误的.但是有解决办法吗?
Note that age
is not declared. The problem I have is that TypeScript doesn't allow this, it gives an assignment error like Property 'age' is missing
. By my understanding, the react.d.ts
definition is wrong in this sense. But is there a solution?
我试过了:
setState({name: "Aaron"} as MyState);
但这给出了同样的错误,即使它 在操场上工作而不会出错.为什么它在 Playground 中有效?有什么想法吗?
But this gives the same error, even though it works in the Playground without giving an error. Why does it work in the Playground? Any ideas?
推荐答案
react.d.ts
定义确实是错误的,直到 支持部分类型.
The react.d.ts
definition is indeed wrong, and cannot be fixed until Partial Types are supported.
问题在于 setState
需要一个部分状态,这是一种与正常状态不同的类型.您可以通过手动指定这两种类型来解决此问题:
The problem is that setState
takes a partial state, which is a different type from normal state. You can solve this by manually specifying both types:
interface MyState {
name: string;
age: number;
}
interface PartialMyState {
name?: string;
age?: number;
}
并手动声明 MyComponent
而不扩展提供的 React Component
类:
And manually declaring MyComponent
without extending the provided React Component
class:
class MyComponent {
state: MyState;
setState(state:PartialMyState): void;
//...
}
这意味着您必须为代码中 Component
的每个子类复制这些函数定义.您可以通过定义一个正确的 Component
类来避免这种情况,该类由附加类型的部分状态概括:
Which means you'll have to duplicate these function definitions for every subclass of Component
in your code. You may be able to avoid this by defining a correct Component
class generalized by an additional type of partial state:
class CorrectComponent<S,P> { // generalized over both state and partial state
state:S;
setState(state:P):void;
//...
}
class MyComponent extends CorrectComponent<MyState,PartialMyState> { }
您仍然需要为您拥有的每种状态类型编写一个部分版本.
You'll still have to write a partial version for every state type you have.
或者,您可以通过将 setState
的参数类型更改为 Object
来使 setState
成为非类型安全的.
Alternatively, you can make setState
non-typesafe by changing its argument's type to Object
.
这篇关于TypeScript 部分接口对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!