There is a way to have code fields which apply only to specific bundles: these are called bundle fields. These are particularly useful for adding computed fields to specific bundles of an entity (more on computed fields in a future blog post).
The API for these is a bit clunky, as it wasn’t finalised for Drupal 8, and it may in fact be completely changed in the future. If that causes you apprehension at implementing bundle fields in your code, it’s worth mentioning that the last patch on that issue was in 2017: it’s a complex problem without many applications, so accordingly doesn’t get much attention.
Bundle fields need to be defined in two places: the field storage, and field definition itself. This is similar to how config fields work; it’s actually the same as base fields, but the BaseFieldDefinition hides this from you as it does double duty. (There is an issue to remove the need to define the storage, but again, not much happening there.)
You also need a field definition class. The entity contrib module provides a BundleFieldDefinition class, but if you don’t want to install that module just for a single class, copy-pasting that class to your custom module is fine too.
(There is a class in core FieldDefinition, which was added for this purpose, however, that requires a storage class to work alongside it, and the issue to provide that has not yet been fixed.)
Once you have that class, how you define the field depends on the entity you’re adding it to.
Bundle fields on your own entity type
In your own entity type, you define the entity class. You can therefore implement the bundleFieldDefinitions() method in that class: