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

Branded types now compatible with declaration option of TS #196

Merged
merged 1 commit into from
Mar 22, 2021

Conversation

yuhr
Copy link
Collaborator

@yuhr yuhr commented Mar 22, 2021

Resolves #195. With this fix, the resulting static type of String.withBrand("BrandedString") will look like string & RuntypeBrand<"BrandedString">. This also makes tooltips more readable, especially for complex types, for example:

export const ID = String.withBrand('ID');
export type ID = Static<typeof ID>;

export const ArrayNonEmpty = <T extends Runtype>(element: T) =>
  Array(element).withConstraint(a => 0 < a.length || 'array must not be empty');

export const IDRequiedAndOptional = Record({ required: ArrayNonEmpty(ID) })
  .And(Partial({ optional: ArrayNonEmpty(ID) }))
  .withBrand('IDRequiedAndOptional');
export type IDRequiedAndOptional = Static<typeof IDRequiedAndOptional>;

Without this fix, the static type of IDRequiedAndOptional was being shown as:

type IDRequiedAndOptional = {
    required: (string & {
        [RuntypeName]: "ID";
    })[];
} & {
    optional?: (string & {
        [RuntypeName]: "ID";
    })[] | undefined;
} & {
    [RuntypeName]: "IDRequiedAndOptional";
}

But now:

type IDRequiedAndOptional = {
    required: (string & RuntypeBrand<"ID">)[];
} & {
    optional?: (string & RuntypeBrand<"ID">)[] | undefined;
} & RuntypeBrand<"IDRequiedAndOptional">

This is not a breaking change, because it's just an interface like following:

export interface RuntypeBrand<B extends string> {
  [RuntypeName]: B;
}

@yuhr yuhr merged commit 146d8f6 into runtypes:master Mar 22, 2021
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

Successfully merging this pull request may close these issues.

Branded types not working with declaration option of TS in some cases
1 participant