Effect CommunityEC
Effect Community3y ago
3 replies
Liam

Creating a Union of Branded Types

Any advice for creating a union of branded types?

I have the following code, but it errors for both approaches:

import * as S from "@effect/schema/Schema";

const brand1 = S.string.pipe(S.brand("brand1"));
//    ^?
const brand2 = S.number.pipe(S.brand("brand2"));
//    ^?

// Argument of type '(BrandSchema<string, string & Brand<"brand1">> | BrandSchema<number, number & Brand<"brand2">>)[]' is not assignable to parameter of type 'Schema<any, any>'.
// Type '(BrandSchema<string, string & Brand<"brand1">> | BrandSchema<number, number & Brand<"brand2">>)[]' is missing the following properties from type 'Schema<any, any>': ast, [TypeId], pipe(2345)
const bothBrands1 = S.union([brand1, brand2]);
//    ^?

const brand3 = S.string.pipe(S.fromBrand(brand1));
//    ^?
const brand4 = S.number.pipe(S.fromBrand(brand2));
//    ^?

// Argument of type '(Schema<string, string & Brand<"brand1">> | Schema<number, number & Brand<"brand2">>)[]' is not assignable to parameter of type 'Schema<any, any>'.
//  Type '(Schema<string, string & Brand<"brand1">> | Schema<number, number & Brand<"brand2">>)[]' is missing the following properties from type 'Schema<any, any>': ast, [TypeId], pipe(2345)
const bothBRands2 = S.union([brand3, brand4]);
//    ^?


I'm enjoying using branded types to represent different IDs in my code, and want to define a method that accepts one of either two ID types, with some validation.
Was this page helpful?