私はこの状況にあり、意味のあるデータ構造の変更はできません。だから私はタグを追加することはできません。 タグなしのタイプを区別する方法はありますか?私はアヒルタイピングを試みましたが、うまくいきません。私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)
}
}
エラーがある参照してください:それは互いに素組合がそうであるように
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
'count'が '0'または' message'では、 ' '''である場合であれば、このアプローチは失敗します。一見すると、私のタイプは、データの構造が変わったように見えるので、私の答えは下降していたと推測しています。しかし、オプションのフィールドを追加することは、あなたが記述したデータと互換性があります。このフォームでは、 '!== undefined'をチェックすることができます。 –