简体   繁体   English

Typescript 传递道具作为对象的键之一 - 值

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

I am using react native and trying to pass one of string values to another component.我正在使用本机反应并尝试将其中一个字符串值传递给另一个组件。

The type object looks like this: object type如下所示:

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

so when I pass a value called operationType I want it to be one of the strings: move , inventory , demand or supply .所以当我传递一个名为operationType的值时,我希望它是字符串之一: moveinventorydemandsupply

the child component would have an interface like this:子组件将具有如下界面:

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

I could use我可以使用

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

but I want it to be dynamic and editable only in one place.但我希望它只能在一个地方动态且可编辑。 What should I do?我应该怎么办?

The best way would be to use an enum instead of an object:最好的方法是使用枚举而不是 object:

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

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

If you want to stick to an object, you can use keyof to get the keys and then get the values:如果您想坚持使用 object,您可以使用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;
}

What about to use enum?如何使用枚举? https://www.typescriptlang.org/docs/handbook/enums.html https://www.typescriptlang.org/docs/handbook/enums.html

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

interface usage:接口使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM