GithubHelp home page GithubHelp logo

maninak / ts-xor Goto Github PK

View Code? Open in Web Editor NEW
100.0 1.0 5.0 458 KB

Compose object types containing mutually exclusive keys, using this generic Typescript utility type.

Home Page: https://app.radicle.at/nodes/seed.radicle.at/rad:z3nP4yT1PE3m1PxLEzr173sZtJVnT

License: MIT License

TypeScript 97.58% Shell 0.21% JavaScript 2.21%
typescript custom-types xor utility-types

ts-xor's People

Contributors

maninak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

ts-xor's Issues

Typescript cannot infer properties are not undefined upon reference

Not sure if this is a bug. This type works as intended for assignment. However:

interface Code {
    code: string;
}

interface Token {
    token: string;
}

type CodeOrToken = XOR<Code, Token>;

const codeOrToken : CodeOrToken = {
    code: 'code'
}

declare function doSomethingWithCode(code: Code) {}

declare function doSomethingWithToken(token: Token) {}

function doSomething(codeOrToken: CodeOrToken) {
    codeOrToken.token
    ? doSomethingWithToken(codeOrToken)
    : doSomethingWithCode(codeOrToken); <-- TS error
}

The last line has the TS error:

Argument of type '(Without<Code, Token> & Token) | (Without<Token, Code> & Code)' is not assignable to parameter of type 'Code'.
  Type 'Without<Code, Token> & Token' is not assignable to type 'Code'.
    Types of property 'code' are incompatible.
      Type 'undefined' is not assignable to type 'string'.

Likewise:

declare function doSomethingWithCode(code: string) {}

declare function doSomethingWithToken(token: string) {}

function doSomething(codeOrToken: CodeOrToken) {
    codeOrToken.token
    ? doSomethingWithToken(codeOrToken.token)
    : doSomethingWithCode(codeOrToken.code); <-- Error
}

Produces the error:

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.

Can anything be done about this?

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

An in-range update of rimraf is breaking the build 🚨

The devDependency rimraf was updated from 2.6.3 to 2.7.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

rimraf is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 2 commits.

  • 250ee15 2.7.0
  • dc1682d feat: make it possible to omit glob dependency

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

XOR based on keys

Hello, thanks for this utility type. However, my usecase is usually to create a type of an object where only certain keys of that same object are mutually exclusive. I wonder if there's any interested to include a type for this? I know it's quite easily possible by creating new types of the object (using omit for instance), but an "API" like this would be a bit easier:

type MutuallyExclusive<T, U extends keyof T> = ...

type BaseButtonProps = {
    primary?: boolean
    destructive?: boolean
    secondary?: boolean
    type: string
}

type ButtonProps = MutuallyExclusive<BaseButtonProps, 'primary' | 'secondary' | 'destructive'>

I created a helper type for this. I've done limited testing, but it seems to work for my use case at least. Would this be something that would be useful to include in this repo?

type MutuallyExlusive<T extends object, U extends keyof T> = Prettify<
    T &
        {
            [K in U]: WithoutObj<Pick<T, U>, Pick<T,K>> & T
        }[U]
>

Use `//@ts-expect-error` to simplify testing approach

  • Use //@ts-expect-error inside *.fail.test files to mark "rejected" test cases and simplify (delete altogether?) unit testing shell script.
  • Consider renaming all tests to just *.test if the extra context on the filename is obsolete
  • Keep current behavior where our test runner continues testing subsequent suits after a failing suit and prints out each one that failed

Let `XOR` take multiple arguments?

There is a nice example of how to use this with more than two types:

// example1.ts

import type { XOR } from https://github.com/maninak/ts-xor

interface A {
  a: string
}

interface B {
  b: string
}

interface C {
  c: string
}

let test: XOR<A, XOR<B, C>>

test = { a: '' }         // OK
test = { b: '' }         // OK
test = { c: '' }         // OK
test = { a: '', c: '' }  // rejected
test = {}                // rejected

Is there a possibility to make the helper more dynamic so you can pass more than two arguments to this helper such as:

type A = { a: string }
type B = { a: string }
type C = { a: string }
type D = { a: string }

let test: XOR<A, B, C, D>

test = { a: '' } // OK
test = { b: '' } // OK
test = { c: '' } // OK
test = { d: '' } // OK
test = { a: '', b: '' } // Rejected
test = {} // Rejected

I'm not a TS expert but isn't there away to spread types using the spread syntax? (...)

Import error "The current file is a CommonJS module [...] the referenced file is an ECMAScript module [...]"

Using TS 5.2 I got

src/services/common/BaseApiConfig.ts:1:15 - error TS2305: Module '"ts-xor"' has no exported member 'XOR'.

1 import type { XOR } from 'ts-xor';
                ~~~

src/services/common/BaseApiConfig.ts:1:26 - error TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("ts-xor")' call instead.
  To convert this file to an ECMAScript module, change its file extension to '.mts', or add the field `"type": "module"` to '/Users/volker/PhpstormProjects/bap-esim/package.json'.

1 import type { XOR } from 'ts-xor';
                           ~~~~~~~~

tsconfig compiler options look like

    "target": "es2022",
    "module": "Node16",
    "outDir": "dist",
    "sourceMap": true,
    "incremental": true,
    "declaration": true,
    "removeComments": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "typeRoots": ["./src/types", "node_modules/@types"],
    "allowJs": false,
    "allowSyntheticDefaultImports": true,
    "baseUrl": "src",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "importHelpers": true,
    "noEmit": false,
    "pretty": true,
    "skipLibCheck": true,

    "strict": false,
    "alwaysStrict": true,
    "strictBindCallApply": true,

Add tests

  • define and implement acceptance tests against the compiler
  • come up with and implement mutant tests against compiler
  • setup a testing procedure hooked up with npm test

Notes:
Some early ideas to be incorporated when working for the above in this TS code-pen

Putting XOR inside of a union type allows any key to be used in object

Hello!

Thank you for this great library!

However, putting XOR inside of a union type:

type Creature = (XOR<T1, T2> | string);

allows any key to be used in objects T1 and T2:

import { XOR } from 'ts-xor';


type Person = {
  name: string;
}

type Animal = {
  nickname: string;
}

type Creature = (string | XOR<Person, Animal>);


// GOOD: doesn't throw error
const creature0: Creature = 'Krusty';

// GOOD: doesn't throw error
const creature1: Creature = {
  name: 'Homer',
};

// GOOD: doesn't throw error
const creature2: Creature = {
  nickname: 'Santa\'s Little Helper',
};

// GOOD: throws error
const creature3: Creature = {
  name: 'Homer',
  nickname: 'Santa\'s Little Helper',
};

// BAD: doesn't throw error
const creature4: Creature = {
  name: 'Homer',
  foo: true,
};

// BAD: doesn't throw error
const creature5: Creature = {
  nickname: 'Santa\'s Little Helper',
  foo: true,
};

Could you please elaborate on this behavior? Is it expected? Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.