打字稿将道具作为对象的键之一传递-值

Typescript Passing prop as one of the objects's keys - values

我正在使用 React Native 并尝试将其中一个字符串值传递给另一个组件。

type 对象如下所示:

export const ScannerAction = {
  move: 'move',
  inventory: 'inventory',
  demand: 'demand',
  supply: 'supply'
};

所以当我传递一个名为 operationType 的值时,我希望它是以下字符串之一:moveinventorydemandsupply .

子组件将具有如下界面:

interface IIProps {
  id: string;
  otherStuff: any;
  operationType: should be the type of ScannerAction
}

我可以用

operationType: 'supply' | 'demand' | 'inventory' | 'move'

但我希望它是动态的并且只能在一个地方编辑。我该怎么办?

使用枚举怎么样? https://www.typescriptlang.org/docs/handbook/enums.html

export enum ScannerAction {
    move = 'move',
    inventory = 'inventory',
    demand = 'demand',
    supply = 'supply'
}

接口使用:

interface IIProps {
    id: string;
    otherStuff: any;
    operationType: ScannerAction
}

最好的方法是使用枚举而不是对象:

enum ScannerAction {
  move = 'move',
  inventory = 'inventory',
  demand = 'demand',
  supply = 'supply'
};

interface IIProps {
  id: string;
  otherStuff: any;
  operationType: ScannerAction
}

如果你想粘在一个对象上,你可以使用keyof获取键然后获取值:

const ScannerAction = {
  move: 'move',
  inventory: 'inventory',
  demand: 'demand',
  supply: 'supply'
} as const; // make this const so that ScannerActionValues becomes a union of all values instead of string

type ScannerActionValues = typeof ScannerAction[keyof typeof ScannerAction];

interface IIProps {
  id: string;
  otherStuff: any;
  operationType: ScannerActionValues;
}