redux 具有跨页成员的TypeScript界面

w3nuxt5m  于 2022-11-12  发布在  TypeScript
关注(0)|答案(2)|浏览(134)

我正在批量导入一堆属性
import * as actionCreators from './billingUtil2';
并且TypeScript正确地标识actionCreators内部的每个导出。是否可以将这些成员“扩展”到一个接口中?理想情况下是这样的,但是有效

interface componentState {
    ...actionCreators
}

我的用例是,我想创建一个React组件,并准确地描述它将从Redux接收的道具的形状。

import * as actionCreators from './billingUtil2';

interface State {
    name: string;
    age: number
}

interface componentState extends State {
    ...actionCreators
}

然后我可以告诉TypeScript期望componentState形式的属性。我在这里的主要目标是避免手动键入每个操作创建者。

xhv8bpkk

xhv8bpkk1#

您可以创建Intersection Type

import * as actionCreators from './billingUtil2';

type MyState = typeof actionCreators & {
    name: string
    age: number
}

或者从上面第二部分的代码中(其中有State接口),您可以执行以下操作

import * as actionCreators from './billingUtil2';

interface State {
    name: string;
    age: number
}

type componentShape = typeof actionCreators & State;

或者你也可以这样做

type acT = typeof actionCreators
interface MyState extends acT {
    name; age;
}

class Comp extends React.Component<{}, MyState> {

}
uqxowvwt

uqxowvwt2#

交叉点类型,在接受的答案中提出的工作,为大多数用例。
但让我们假设(一个非常常见的用例)actionCreators类型已经具有name属性,但它是不同的类型。

interface ActionCreators {
  name: string[]; // list of strings which may include 1st to last name
  gender: string;
  height: number;
}

然后,您将收到错误消息,指出ActionCreators和State不兼容。
若要修正此问题,您可以在使用交集类型策略之前,使用Mapped Types从ActionCreators移除名称。

// Remove the 'name' property
type RemoveNameField<Type> = {
    [Property in keyof Type as Exclude<Property, "name">]: Type[Property]
};

type State = RemoveNameField<ActionCreators> & { name: string; age: number; };

相关问题