When it might be ok to use a mixed type

It serves a useful purpose

Joel Clermont
Joel Clermont
2023-12-18

When first introducing types to a Laravel application, you often run into some places in the code that are a little messy and not easily typed.

One option would be to refactor that code to a design that can have clear types assigned, but that can slow down your process and introduce some risk.

Another option, and one we use occasionally, is to temporarily use the mixed type instead. mixed is PHP's way of saying that any type could satisfy the type definition.

You might wonder, "Isn't this the same thing as just not specifying a type at all?"

Yes! As far as PHP is concerned, it is the same, but in terms of communication in the code base, mixed is a more explicit way of saying: "We looked at this code, and it can't be typed right now. We're temporarily moving on."

If you just leave the type off, it's hard to differentiate the conscious decision of leaving it untyped with a function that hasn't been evaluated for type definitions yet.

They are functionally equivalent, but specifying "mixed" conveys intent whereas a missing type could just be missing by mistake.

We tighten types over time, but in those early days, I find this is a useful approach.

Here to help,

Joel

P.S. Have you tried introducing Larastan to a project and got stuck or ran into a million confusing errors? We can help!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.