简体   繁体   English

如何确保属性的值是预定义的 object 中的值之一?

[英]How do i ensure that the value of a property is one of the value in an pre-defined object?

I am using react with typescript and would like to have to make sure the state type be limited to the values in an object like so我正在使用与 typescript 反应,并希望确保 state 类型限制为 object 中的值,就像这样

Consider考虑

 const [proessStatus, setProcessStatus] = useState<ProcessState>();

The useState must accept as argument only the values from the ProcessState Object. useState 必须仅接受来自 ProcessState Object 的值作为参数。

const ProcessState = {
    NOT_STARTED: 'NOT_STARTED',
    STARTED: 'STARTED',
    LOADING: 'LOADING',
    FINISHED: 'FINISHED'
}

Is there a way to ensure this in typescript through Interfaces or any other means.有没有办法通过接口或任何其他方式在 typescript 中确保这一点。

Yes, use string-based enums please!是的,请使用基于字符串的枚举!

enum ProcessState {
  NOT_STARTED = 'NOT_STARTED',
  STARTED = 'STARTED',
  LOADING = 'LOADING',
  FINISHED = 'FINISHED'  
}

They are type-safe in their values (so validation happens at compile time).它们的值是类型安全的(因此验证发生在编译时)。 You can use the Enum object itself as a normal object at runtime.您可以在运行时将枚举 object 本身用作普通的 object。 If you need additional runtime validation you can use Object.values(ProcessState) to get the valid values.如果您需要额外的运行时验证,您可以使用Object.values(ProcessState)来获取有效值。 And you can use it with the Record<SomeEnum, SomeValueType> type to create type safe maps etc.您可以将它与Record<SomeEnum, SomeValueType>类型一起使用来创建类型安全映射等。

Use enum and use it as the type of the argument of the function使用 enum 并将其用作 function 的参数的类型

enum ProcessState {
  NOT_STARTED = 'NOT_STARTED',
  STARTED = 'STARTED',
  LOADING = 'LOADING',
  FINISHED = 'FINISHED'  
}

function useState(p: ProcessState) {

   ...

}

useState(ProcessState.STARTED)

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

相关问题 如何针对预定义的对象属性名称使用JavaScript提示框输入值? - How to use a JavaScript prompt box input value against a pre-defined object property name? 如何配置Highcharts,使其显示一些预定义的值 - How to configure Highcharts so that it displays some pre-defined value 将设置值添加到预定义变量 - Adding set value to pre-defined variable Javascript-传递预定义值 - Javascript - Passing pre-defined value 使用预定义的方法来更改对象Javascript的属性 - Using a pre-defined method to change a property of an object Javascript JavaScript 在未预定义维度的多维数组中设置值 - JavaScript Set value at multidimensional array where dimensions are not pre-defined 如何在mongodb模式中使用预定义的值创建字段,并让用户使用单选按钮选择值 - How create a field in mongodb schema with pre-defined values, and make the user choose the value with a radio button 在给定预定义变量的情况下,如何在jQuery中计算出一定数量 - How do I count up to a certain number in jQuery given a pre-defined variable 如何返回当天的预定义daterangepicker范围? - How do I return the pre-defined daterangepicker range the current day falls in? 如何将变量添加到预定义的 function 的 scope 中? - How do you add variables to the scope of a pre-defined function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM