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

Fix intersections with primitives to add support for branded/flavored types #110

Open
etler opened this issue Sep 10, 2021 · 1 comment
Open

Comments

@etler
Copy link

etler commented Sep 10, 2021

"Branding" and "Flavoring" is a technique to achieve nominal like typing in typescript

It works by using an object intersection with a primitive. Since objects can be intersected with anything, this does not create a never type, but instead the type expects the primitive, and since objects can't be primitives, only the primitive type is allowed to be assigned. Since the object type information is still part of the type, those branded or flavored primitives cannot then be reassigned to another type, achieving a type that acts like a nominal type.

Among other things, this feature is very helpful for creating id types that cannot accidentally be misassigned. We use this feature for our ids to gain additional type safety so we do not accidentally use the wrong kind of id for a query that does not expect it.

Typescript-is does not seem to support this feature, and incorrectly expects there to be an object as opposed to the primitive. This seems to be an error with how intersections are parsed when they are paired with a primitive.

Currently, creating an assertion like:

type PersonId = { _type?: "person" } & string
assertType<PersonId>("person_id_abcd") //

will fail with the error: TypeGuardError: validation failed at $: expected an object, found: 'person_id_abcd' expecting the input to be an object, however, this behavior does not match the behavior of typescript:

type PersonId = { _type?: "person" } & string
const pId1: PersonId = "person_id_abcd" // valid
const pId2: PersonId = {} // error
const pId3: PersonId = { _type: "person" } // error

The typescript compiler expects PersonId to be a string, and attempting to assign an object to it should result in an error, meaning the behavior of typescript-is in this specific scenario is invalid.

@MurhafElmasri
Copy link

we faced this issue with our work, so I had to solve it.
you can check pull request #120.

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

No branches or pull requests

2 participants