# Handling typing for optional dependencies

**URL:** <https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807>\
**Category:** Crystal Contrib\
**Created:** [March 22, 2026, 2:00am UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807 "2026-03-22T02:00:55Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![Blacksmoke16](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/blacksmoke16/32/1241_2.png) [@Blacksmoke16](https://forum.crystal-lang.org/u/Blacksmoke16)\
**Post date:** [March 22, 2026, 2:00am UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/1 "2026-03-22T02:00:55Z")

</div>

So I have been exploring the idea of de-coupling some of the Athena components from the framework. In other words, make some of them optional and not installed by default. E.g. one of the framework services has a constructor like:

```crystal
def initialize(
  @serializer : ASR::SerializerInterface,
  @validator : AVD::Validator::ValidatorInterface,
  @annotation_resolver : ATH::AnnotationResolver,
); end

```

The approach I was thinking of was, say the `validator` component was optional, that parameter could be typed as `AVD::Validator::ValidatorInterface? = nil` and would be able to detect that that component is installed to wire it up so it can be provided to the constructor.

However, the problem with this is of course is if that component isn’t installed then the `AVD::Validator::ValidatorInterface` is not going to exist and the compiler would error because of the unknown type. My original plan to handle this was to have the framework just stub out the type so it exists but doesn’t have any implementation, nor be used as a marker that the component _is_ installed so the `@validator` would be `nil`. The main con of that is I’d need to keep track of what types need to be stubbed, might get complicated when they’re not modules due to needing to also stub superclass, etc.

Another idea I thought of, not entirely sold on it as of yet either, is the idea of adding an annotation that would suppress the unknown type error. E.g. `@[SomeAnnotationName] @validator : AVD::Validator::ValidatorInterface? = nil` would not error if that type is missing at compile time, and just resolve to `nil`. This approach would be a bit more straightforward and obvious that the type is optional.

EDIT: Or maybe instead of an annotation, could be its own syntax? `@validator : ?AVD::Validator::ValidatorInterface? = nil`? 🤷

Yet another approach would be to of course leverage `{% if ... %}` macro to define a constructor that just entirely excludes that parameter if the component isn’t installed, but this just feels less than idea due to how verbose it would have to be, esp if more than one parameter is optional.

Curious what others thoughts are on how to best handle this!

---

<div class="post-metadata">

**Author:** ![bcardiff](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/bcardiff/32/3_2.png) [@bcardiff](https://forum.crystal-lang.org/u/bcardiff)\
**Post date:** [March 22, 2026, 4:14am UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/2 "2026-03-22T04:14:24Z")

</div>

Did you consider defining a type if it was not defined by that time? That would work as long as the require are in a specific order. But it would be less convoluted usage of if macros I believe.

---

<div class="post-metadata">

**Author:** ![tsornson](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/tsornson/32/1651_2.png) [@tsornson](https://forum.crystal-lang.org/u/tsornson)\
**Post date:** [March 22, 2026, 4:21am UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/3 "2026-03-22T04:21:13Z")

</div>

Rather than doing something special at the type restriction level, I think it would be more comfortable to do something at the top level to declare optional types that would default to something like `alias <optional type> = Nil` if `<optional type>.resolve` (or whatever the macro method is) doesn’t, well, resolve.

I’m not sure how the rest of the compilation would work out, though, given `<optional type that turned into Nil>.not_nil!.some_method`could be written and `some_method` obviously doesn’t exist on `Nil`. I guess that would be a forcing function to not use the `.not_nil!` method for these kinds of types 😁

Or from another angle, this could be an argument for needing some way to declare at the type restriction level “I don’t care what the type is, so long as method `some_metho` exists on it”, and then the type of the instance becomes moot so long as it has a specific _shape_.

---

<div class="post-metadata">

**Author:** ![straight-shoota](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/straight-shoota/32/36_2.png) [@straight-shoota](https://forum.crystal-lang.org/u/straight-shoota)\
**Post date:** [March 22, 2026, 2:09pm UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/4 "2026-03-22T14:09:21Z")

</div>

The compiler already ignores overloads with type restrictions that don’t exist because they can never match.

This is totally fine:

```cr
def foo(x : Int32)
end

def foo(x : NotExist)
end

foo 1

```

When merging both overloads into one, the missing type is a problem though:

```auto
def foo(x : Int32 | NotExist)
end
 
foo 1 # Error: undefined constant NotExist

```

Perhaps this should be valid code?  
We could enhance the compiler to ignore undefined members in a union type restrictions. Semantically, this makes sense: `NotExist` is undefined, thus we can never encounter an instance of it. We can ignore it and produce an entirely valid program.

I’m not sure how well this plays with type annotations in other places than method parameters, though.

---

<div class="post-metadata">

**Author:** ![bcardiff](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/bcardiff/32/3_2.png) [@bcardiff](https://forum.crystal-lang.org/u/bcardiff)\
**Post date:** [March 22, 2026, 2:32pm UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/5 "2026-03-22T14:32:12Z")

</div>

> [@straight-shoota](#):
>
> Perhaps this should be valid code?

I don’t think so. It would be indistinguishable from typos

---

<div class="post-metadata">

**Author:** ![Blacksmoke16](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/blacksmoke16/32/1241_2.png) [@Blacksmoke16](https://forum.crystal-lang.org/u/Blacksmoke16)\
**Post date:** [March 22, 2026, 3:17pm UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/6 "2026-03-22T15:17:34Z")

</div>

> [@bcardiff](#):
>
> Did you consider defining a type if it was not defined by that time?

Would this be any different than defining them regardless and just let monkeypatching handle merging in the implementation when the component is required?

> [@tsornson](#):
>
> Rather than doing something special at the type restriction level, I think it would be more comfortable to do something at the top level to declare optional types that would default to something like `alias <optional type> = Nil`

Oo I never considered making the type an alias to another type 👀. I tried this out with:

```crystal
alias Athena::Validator::Validator::ValidatorInterface = Nil

# ...

def initialize(
  @serializer : ASR::SerializerInterface,
  @annotation_resolver : ATH::AnnotationResolver,
  @validator : Athena::Validator::Validator::ValidatorInterface? = nil,
); end

```

Unfortunately, compiler doesn’t like this:

```txt
 213 | @validator : Athena::Validator::Validator::ValidatorInterface? = nil,
       ^
Error: instance variable @validator of SomeType was inferred to be Nil, but Nil alone provides no information

```

> [@tsornson](#):
>
> Or from another angle, this could be an argument for needing some way to declare at the type restriction level “I don’t care what the type is, so long as method `some_metho` exists on it”, and then the type of the instance becomes moot so long as it has a specific _shape_.

Reminds me a bit of some of the implicit interface stuff talked about in [[RFC] Standardized Abstractions](https://forum.crystal-lang.org/t/rfc-standardized-abstractions/4414).

> [@straight-shoota](#):
>
> Perhaps this should be valid code?

This would work quite well for this use case yea! Tho as I brought up earlier maybe there would be a world in which it’s more opt-in via new syntax/annotation/type or something as to @bcardiff’s point to silently ignoring errors when you might actually want them.

- Annotation: `@[Optional] @validator : ValidatorInterface? = nil`
- Syntax: `@validator : ?ValidatorInterface? = nil` (prefix with `?` or something along those lines)
- New Type: `@validator : Optional(ValidatorInterface) = nil` (Tho might run into the same problem as aliasing it to `Nil`)

> [@straight-shoota](#):
>
> I’m not sure how well this plays with type annotations in other places than method parameters, though.

Yea, looking at the code for my use case again, this wouldn’t be a 100% solution as there is still code later on doing like:

```crystal
if object.is_a?(Array) && constraints && !constraints.is_a?(Athena::Validator::Constraints::All)
  constraints = Athena::Validator::Constraints::All.new constraints
end

```

Which I would expect to error when not used as well. Granted guarding some block of code with macro if logic would be a lot more straightforward than the constructor. So may still be useful to have.

* * *

Another idea would be to do some refactoring to extract the logic into another type that could be provided/called but that just would no-op when the `validator` component isn’t installed. Tho I suppose this is really just moving the macro if logic to somewhere else and not really eliminating the problem.

Either way it’s def seeming like macro if logic is going to be the best option, as even if i were to stub out the types, will also have to handle constructors of those types and such as well and that’s just not worth the effort.

---

<div class="post-metadata">

**Author:** ![bcardiff](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/bcardiff/32/3_2.png) [@bcardiff](https://forum.crystal-lang.org/u/bcardiff)\
**Post date:** [March 22, 2026, 11:40pm UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/7 "2026-03-22T23:40:43Z")

</div>

> [@Blacksmoke16](#):
>
> Would this be any different than defining them regardless and just let monkeypatching handle merging in the implementation when the component is required?

I think that class vs. struct and inheritance can get in the way of partial type declarations.

In [crystal-env/src/crystal-env/core.cr at master · crystal-lang/crystal-env · GitHub](https://github.com/crystal-lang/crystal-env/blob/master/src/crystal-env/core.cr) I added some logic to implement a Default value. Not the same problem put I would use a similar solution.

In a broader sense I think that your case falls into how to support plugins, optional or peer dependencies. It’s a use case that is not first class in crystal or shards and hence you are getting some friction on how to encode that with the available tools. Maybe focusing on that problem, and to make it first class would lead to nicer solutions.

---

<div class="post-metadata">

**Author:** ![straight-shoota](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/straight-shoota/32/36_2.png) [@straight-shoota](https://forum.crystal-lang.org/u/straight-shoota)\
**Post date:** [March 23, 2026, 12:23am UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/8 "2026-03-23T00:23:33Z")

</div>

My first example could also hide a typo, though.  
Expanded a bit for demonstration.

```cr
class Foo; end
class Bar < Foo; end

def foo(x : Foo)
  1
end

def foo(x : Bat) # <- This could be mistyped `Bar`
  2
end

foo Bar.new # => 1

```

This has always been okay, even though it could easily hide a potential mistake.  
That doesn’t automatically legitimize introducing something similar, but I think it could be an argument to not entirely discount the idea.

---

<div class="post-metadata">

**Author:** ![ysbaddaden](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/ysbaddaden/32/2252_2.png) [@ysbaddaden](https://forum.crystal-lang.org/u/ysbaddaden)\
**Post date:** [March 23, 2026, 11:25am UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/9 "2026-03-23T11:25:33Z")

</div>

If you make interfaces then you can have swappable objects, and use fake (or null) types by default:

```crystal
module Foo
  abstract class Interface
    abstract def something
  end

  class Default < Interface
    def something; end
  end

  # use singleton so it's initialized once per program
  class_getter(default : self) { Default.new }
end

def foo(foo : Foo::Interface = Foo.default)
end

```

When the actual interface is required, it can replace the default constructor:

```crystal
require "foo/interface"

module Foo
  class Real < Interface
    def something
      puts "I'm doing something"
    end
  end

  # no singleton, we want distinct objects
  def self.default : self
    Real.new
  end
end

```

It’s kinda verbose, requires boilerplate and ceremony, but then you don’t have to deal with nils at runtime + the optimizer will drop the empty calls by default.

Bonus: the interface is swappable (can implement alternative, can use mock in specs, …).

---

<div class="post-metadata">

**Author:** ![paulocoghi](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/paulocoghi/32/1429_2.png) [@paulocoghi](https://forum.crystal-lang.org/u/paulocoghi)\
**Post date:** [March 24, 2026, 9:08am UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/10 "2026-03-24T09:08:52Z")

</div>

This is a beautiful example of a good usage of design patterns.

I am not in favor of recklessly applying design patterns everywhere / in any situation, as some advocate for, but I am fully in favor of using one when the scenario clearly asks for it.

This is one of these scenarios. Beautiful implementation @ysbaddaden! And the boilerplate is fully justified.

---

<div class="post-metadata">

**Author:** ![yxhuvud](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/yxhuvud/32/27_2.png) [@yxhuvud](https://forum.crystal-lang.org/u/yxhuvud)\
**Post date:** [April 26, 2026, 9:04am UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/11 "2026-04-26T09:04:10Z")

</div>

Regardless I’m happy to see people start thinking about not just how to build good shards, but how to build shards that integrate well with other shards (in the case of blacksmoke intra-project shards, but it is just as relevant for cross-project shard integration). There are usually several different ways to do it, but it doesn’t feel like there has crystallized patterns that can be considered ideomatic yet.

I think it will be increasingly common (including the very much related ‘on platform X I will use shard A, but on platform Y I will use shard B’).

And I’m happy to see the dispatch example, I didn’t know that accepted undefined types, that definitely adds to the options available.

---

<div class="post-metadata">

**Author:** ![Blacksmoke16](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/blacksmoke16/32/1241_2.png) [@Blacksmoke16](https://forum.crystal-lang.org/u/Blacksmoke16)\
**Post date:** [October 11, 2026, 11:31pm UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/12 "2026-10-11T23:31:02Z")

</div>

So I recently got back into working on this from the Athena side of things. Ended up getting things into a state that I really like a lot. However having more official/built-in support for some of this would make things even better.

### Optional Type References

One of the bigger wins would be this

> [@Blacksmoke16](#):
>
> Tho as I brought up earlier maybe there would be a world in which it’s more opt-in via new syntax/annotation/type or something as to @bcardiff’s point to silently ignoring errors when you might actually want them.
> 
> - Annotation: `@[Optional] @validator : ValidatorInterface? = nil`
> - Syntax: `@validator : ?ValidatorInterface? = nil` (prefix with `?` or something along those lines)
> - New Type: `@validator : Optional(ValidatorInterface) = nil` (Tho might run into the same problem as aliasing it to `Nil`)

This would allow defining a service using say `@[Optional] AVD::Validator::ValidatorInterface? = nil` and have things just work. If that type exists and you provide it it’ll use it. If it doesn’t exist or you don’t provide it, it’ll just skip validation.

### Optional Dependencies

Another area that would be helpful is how to have shards validate the versions of optional dependencies. E.g. the `mercure` component’s bundle depends upon `http_kernel` component, but not the actual shard itself. It’s currently setup as an implicit dependency that’ll just fail if you try to require that file w/o having it already installed. It would be nice if there was a way to define like “the mercure component requires `http_kernel` version `~> 0.4.0` that gets checked if the user application is installing it, otherwise is just ignored.” This defines a version floor without having to actually pull in the dependencies.

---

<div class="post-metadata">

**Author:** ![ysbaddaden](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/ysbaddaden/32/2252_2.png) [@ysbaddaden](https://forum.crystal-lang.org/u/ysbaddaden)\
**Post date:** [October 12, 2026, 10:44am UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/13 "2026-10-12T10:44:46Z")

</div>

Optional dependencies in Shards would be great. Following Rust/Cargo, it could be a mere `optional: true` property.

---

<div class="post-metadata">

**Author:** ![Blacksmoke16](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/blacksmoke16/32/1241_2.png) [@Blacksmoke16](https://forum.crystal-lang.org/u/Blacksmoke16)\
**Post date:** [October 12, 2026, 5:04pm UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/14 "2026-10-12T17:04:59Z")

</div>

Created [[RFC] Optional Dependencies · Issue #735 · crystal-lang/shards · GitHub](https://github.com/crystal-lang/shards/issues/735) to start the discussion around that side of things.

---

<div class="post-metadata">

**Author:** ![Blacksmoke16](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/blacksmoke16/32/1241_2.png) [@Blacksmoke16](https://forum.crystal-lang.org/u/Blacksmoke16)\
**Post date:** [October 12, 2026, 6:11pm UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/15 "2026-10-12T18:11:06Z")

</div>

> [@Blacksmoke16](#):
>
> - Annotation: `@[Optional] @validator : ValidatorInterface? = nil`
> - Syntax: `@validator : ?ValidatorInterface? = nil` (prefix with `?` or something along those lines)
> - New Type: `@validator : Optional(ValidatorInterface) = nil` (Tho might run into the same problem as aliasing it to `Nil`)

Actually as I thought more about this, the con of all of these is you’d prob have to do this everywhere the type is defined, which isn’t super ideal. New idea is some top level construct that would be de-coupled from existing syntax and handle things globally. E.g. `optional_type ValidatorInterface`. May work on a PoC here soon.

---

<div class="post-metadata">

**Author:** ![Blacksmoke16](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/blacksmoke16/32/1241_2.png) [@Blacksmoke16](https://forum.crystal-lang.org/u/Blacksmoke16)\
**Post date:** [October 18, 2026, 12:31am UTC](https://forum.crystal-lang.org/t/handling-typing-for-optional-dependencies/8807/16 "2026-10-18T00:31:21Z")

</div>

> [@tsornson](#):
>
> declare optional types that would default to something like `alias <optional type> = Nil` if `<optional type>.resolve` (or whatever the macro method is) doesn’t, well, resolve.

This also worked out quite well, but used `NoReturn` instead of `Nil` to avoid making things nilable and `NoReturn` is just excluded from unions and such so works out a bit better I found.
