typescript-is icon indicating copy to clipboard operation
typescript-is copied to clipboard

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

Open etler opened this issue 2 years ago • 1 comments

"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.

etler avatar Sep 10 '21 01:09 etler

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

MurhafElmasri avatar Dec 21 '21 16:12 MurhafElmasri