如何使用 Typescript 在 React 项目中集中进行接口初始化

How to centralize interface initialization in React project with Typescript

我在 Typescript 中有一个 React 项目,在我的许多组件中我使用 State:

中的接口
interface Item {
    selectedValue: string
    originalSelectedValue: string
    loading: boolean
    disabled: boolean
    isValid?: boolean
}

interface State {
   itemInstance: Item
}

在每个组件中,我使用 constructor 来初始化接口的实例:

constructor(props: Props) {
        super(props);

        let itemInstance: Item = {
             selectedValue: '',
             originalSelectedValue: '',
             loading: true,
             disabled: false,
             isValid?: false
        };

        this.state = {
           itemInstance: itemInstance
        }
}

由于我需要为每个组件重复此初始化,而不是 copy/pasting 每个组件中的代码,我试图找到一种集中初始化的方法。由于接口无法实现,我想实现某种 Factory Method Pattern 而无需使用 class:

     export const getItemInstance = (): Item  => {
        return ({
                 selectedValue: '',
                 originalSelectedValue: '',
                 loading: true,
                 disabled: false,
                 isValid?: false
       });
    }

尽管我不是很喜欢这个解决方案,因为对于每个接口我都需要创建另一个 file/component 来实现初始化。有人知道在 Typescript 中实现此行为的模式吗?

我知道你提到你不想使用 class 但我可能只是介绍一个 class 来实现接口。然后你只需通过一行创建一个实例:

interface IItem {
    selectedValue: string
    originalSelectedValue: string
    loading: boolean
    disabled: boolean
    isValid?: boolean
}

class DefaultItem implements IItem {
  constructor(
    public selectedValue = '',
    public originalSelectedValue = '',
    public loading = true,
    public disabled = false,
    public isValid = false
  ) {}
}

然后在你的组件中:

constructor(props: Props) {
  super(props);

  const itemInstance = new DefaultItem();

  this.state = {
    itemInstance
  };
}

不仅这样读起来更好,而且当您想为所有实例更改一个特定 属性 的默认值时,您可以在一个地方进行。

您可以使用简单的行进行初始化:

interface IInterface{
    first: number;
    second: string;
}

然后

var ourObject = {} as IInterface
var ourObjectArray = [] as Array<IInterface>

在您的情况下,下面是完整代码:

interface Item {
    selectedValue: string
    originalSelectedValue: string
    loading: boolean
    disabled: boolean
    isValid?: boolean
}

interface State {
   itemInstance: Item
}


constructor(props: Props) {
        super(props);

        this.state = {
           itemInstance: {} as Item
        }
}