0

I have the following types and conversion function:

type LeftRightField = null |
    { left: null, right: number } |
    { left: number, right: null } |
    { left: number, right: number }

type LeftRightArray = [null, number] |
    [number, null] |
    [number, number] |
    null

const fmtField = function (field: LeftRightField): LeftRightArray {
    const rightField = field?.right ?? null
    const leftField = field?.left ?? null
    return (leftField == null && rightField == null) ? null : [leftField, rightField]
}

Playground

However this fails with

Type 'number | null' is not assignable to type 'null'.
Type 'number' is not assignable to type 'null'

What is the correct way to do the conversion ?

1 Answer 1

5

This looks like an instance of TypeScript not being able to keep track of what I've been calling correlated types. In your case, leftField and rightField are both of the union type number | null. Unfortunately, the compiler does not consider them together when you do type guards. It treats them as uncorrelated, so [leftField, rightField] is seen as type [number | null, number | null] even though the [null, null] subtype is an impossibility.

The only "right" thing to do here, other than just giving up and asserting that what you are doing is safe like this:

return (leftField === null && rightField === null) ? null :
 [leftField, rightField] as LeftRightArray;

would be to refactor the code into possibly-redundant separate code paths that the compiler can verify with control flow analysis:

return (leftField === null) ? (
 rightField === null ? null : [leftField, rightField]
) : [leftField, rightField];

If you're just using two fields this is fine. If you're using many more than that, the redundancy is probably too much and you should just assert and move on.

Playground link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.