[英]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.