Unrelated unions without tags

I have this situation and it makes no sense for a significant change in the data structure. Therefore, I cannot add the tag. Is there a way to distinguish types without a tag? I tried withholding, but that didn't work. See My Example

type Result = Done | Error; // a disjoint union type with two cases
type Done = { count: number }
type Error = { message: string }

const doSomethingWithDone = (obj: Done) => {/*...*/}
const doSomethingWithError = (obj: Error) => {/*...*/}

const f = (result: Result) => {
  if (result.count) {
    doSomethingWithDone(result)
  } else {
    doSomethingWithError(result)
  }
}

Errors:

 5: const doSomethingWithDone = (obj: Done) => {/*...*/}
                                      ^ property `count`. Property not found in
 10:     doSomethingWithDone(result)
                             ^ object type 
 6: const doSomethingWithError = (obj: Error) => {/*...*/}
                                       ^ property `message`. Property not found in
 12:     doSomethingWithError(result)
                              ^ object type
+4
source share
2 answers

This makes sense, since your typings don't say it Donecan't have the count property.

Using exact object types seems to partially work, in the sense that it corrects correctly, as you can see in this example . Unfortunately, you also need to check in else.

Augustinlf

0
source

, , . . ,

const x: Error = {message: 'foo', count: 'bar'};
f(x);

, x. , , - Error, message, , . , count , Done.

:

type Result = Done | Error; // a disjoint union type with two cases
type Done = {| count: number |}
type Error = {| message: string |}

const doSomethingWithDone = (obj: Done) => {/*...*/}
const doSomethingWithError = (obj: Error) => {/*...*/}

const f = (result: Result) => {
  if (result.count) {
    doSomethingWithDone(result)
  } else if (result.message) {
    doSomethingWithError(result)
  }
}

// Expected error. Since Error is an exact type, the count property is not allowed
const x: Error = {message: 'foo', count: 'bar'};
f(x);

( tryflow)

, , , else else if. , , , . , , , , .

+1

Source: https://habr.com/ru/post/1669813/


All Articles