Before posting an issue on github, I wanted to get some feedback here first.
I'm currently developing a component entity system for a game using typescript. From what I've seen, component entity systems in javascript and typescript can lack type safety, so I have an idea to address this issue.
My plan is to create an Entity type for each system that relies on multiple components. Each Entity type will define the properties that entities processed by that system should have. These Entity types will then be combined into one unified Entity union type.
export type Entity =
CameraManagerEntity |
CollisionManagerEntity |
HoleManagerEntity |
ParentManagerEntity | ...
Within a system, I want to be able to assert that certain properties exist on an entity and have typescript infer the correct type based on that assertion. For instance, if the CameraManager exports:
interface CameraManagerEntity {
foo: boolean,
bar: number
}
And no other type in the Entity union has a "foo" parameter. My expectation is that checking for "foo" within an entity should allow access to "bar" without triggering a type error:
function processEntity(entity: Entity) {
if ("foo" in entity) {
return entity.bar; // <-- Type error.
}
}
Is my approach flawed? It seems like the compiler should be able to determine the specific Entity type based on context. However, it appears that this concept doesn't align with how typescript currently functions. Are there alternative methods to achieve my goal? Appreciate any insights.
Edit: I am familiar with user-defined type guards, but I'm hoping to avoid manual guard implementation as I believe the compiler already possesses the necessary information.