Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

XOR is expressible in TypeScript #24

Open
kshahkshah opened this issue Nov 21, 2018 · 2 comments
Open

XOR is expressible in TypeScript #24

kshahkshah opened this issue Nov 21, 2018 · 2 comments

Comments

@kshahkshah
Copy link

Describe the bug

// The members data and errors MUST NOT coexist in the same document.
// ⛔️ NOT EXPRESSIBLE IN TYPESCRIPT
// If a document does not contain a top-level data key,
//    the included member MUST NOT be present either.
// ⛔️ NOT EXPRESSIBLE IN TYPESCRIPT

is not true any longer

To Reproduce

const foo: Document = {
  errors: [{
    status: 200
  }],
  data: {
    type: 'foo',
    id: '123',
    attributes: {
      foo: 'bar',
      baz: 'biz'
    }
  },
  included: [],
  meta: {
    foo: 'bar'
  }
}

is valid and should not be

Additional context

type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;

interface DocWithDataAndOptionalMeta extends DocWithData{
  meta?: object;
}
interface DocWithErrorsAndOptionalMeta extends DocWithErrors {
  meta?: object;
}

type JSONAPIDocument = XOR<DocWithErrorsAndOptionalMeta, DocWithDataAndOptionalMeta>;

I believe gets you what we want. I can open a PR, was just not certain about how to handle meta. It seems fine to have meta included in a top level response w/errors present or with a 'normal' doc

@kshahkshah
Copy link
Author

Without and XOR lifted from: microsoft/TypeScript#14094 (comment)

@mike-north
Copy link
Owner

mike-north commented Nov 21, 2018

This is great! I'll need us to do some performance testing since this increases the complexity of all JSONAPI resource types (i.e., "document with data") significantly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants