arktypea
arktype16mo ago
errata

extracting redux-like actions from type.enumerated discriminated union

Trying unsuccessfully to convert some redux/reducer-like "action" object types to arktype:

type TestAction1 = { type: 'ACTION_1', value: number }
type TestAction2 = { type: 'ACTION_2', name: string}
type TestAction = TestAction1 | TestAction2

function CreateTestAction1(): Extract<TestAction, {type: 'ACTION_1'}> {
    return { type: 'ACTION_1', value: 3 }
}

const testAction1 = CreateTestAction1() // type === TestAction1



Below is how I did the conversion. The Extract on the type.enumerated results in a never and I don't follow why.


const ArkAction1 = type({ type: type.unit("ACTION_1"), value: type.number })
const ArkAction2 = type({ type: type.unit("ACTION_2"), name: type.string })
const ArkAction = type.enumerated(ArkAction1, ArkAction2)
type ArkAction = type.infer<typeof ArkAction>

function CreateArkAction1(): Extract<ArkAction, { type: 'ACTION_1'}>  {
    return { type: 'ACTION_1', value: 3 } // type not assignable to never
}


If I define the action union type in vanilla TS (from the ark inferred types) the extract works as expected:

type ArkAction1 = type.infer<typeof ArkAction1>
type ArkAction2 = type.infer<typeof ArkAction2>
type ArkAction = ArkAction1 | ArkAction2


Am I holding it wrong?
Was this page helpful?