Effect CommunityEC
Effect Community3y ago
19 replies
imagio

Union Type with Fixed T Value

Union type question -- I have a union type that takes a generic for the discriminator, but one of the cases in that union has a fixed T (it's only valid for one value of T). That causes issues when trying to pass around this generic union type. Concrete example:

type AnyTableName = "foo" | "bar"

class ByIdQuery<T extends AnyTableName > extends Data.TaggedClass("ByIdQuery")<{
    id: string
    tableName: T
}> { }

class FooSpecificQuery extends Data.TaggedClass("FooSpecificQuery")<{ userId: string }> {
    tableName = "foo" as const
}

type AnyQueryType<T extends AnyTableName> = ByIdQuery<T> | FooSpecificQuery

const resolveAny = <T extends AnyTableName>(query: AnyQueryType<T>): T => {
    // Error: Type '"foo" | T' is not assignable to type 'T'.
    // '"foo" | T' is assignable to the constraint of type 'T',
    // but 'T' could be instantiated with a different subtype of constraint 'AnyTableName'.
    return query.tableName
}

How do you handle this case where a union member is only valid for one value of T?
Was this page helpful?