Reuse types.union and TS union #1752
Replies: 2 comments 5 replies
-
For things like statuses, you can use the
|
Beta Was this translation helpful? Give feedback.
-
How about a self-implemented const SOME_STATUS = ['active', 'suspended', 'pending'] as const
type SomeStatus = typeof SOME_STATUS[number]
// type SomeStatus = "active" | "suspended" | "pending"
function enumeration<T extends string>(
name: string,
values: T[] | readonly T[]
): ISimpleType<T> {
const source = Array.isArray(values) ? values : Object.keys(values)
const literals = source.map(value => types.literal(value))
const union = types.union(...literals)
union.name = name
return union
}
const SomeStatus = types.model('SomeStatus', {
status: enumeration('some', SOME_STATUS),
})
const someStatus = SomeStatus.create({
status: 'active',
// (property) status: "active" | "suspended" | "pending"
}) PS This is just my personal workaround demo, I haven't thought about the error handling or other more serious things under the hood. |
Beta Was this translation helpful? Give feedback.
-
I want to have one 'source of truth' - either model field, or union type itself
How can I do it?
Beta Was this translation helpful? Give feedback.
All reactions