Skip to content

Commit ae79e6c

Browse files
Support parameter passing in component constructor (#2158)
* feat: support parameter passing in component constructor
1 parent 5669ab9 commit ae79e6c

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

packages/core/src/Entity.ts

+13-2
Original file line numberDiff line numberDiff line change
@@ -203,11 +203,15 @@ export class Entity extends EngineObject {
203203
/**
204204
* Add component based on the component type.
205205
* @param type - The type of the component
206+
* @param args - The arguments of the component
206207
* @returns The component which has been added
207208
*/
208-
addComponent<T extends Component>(type: new (entity: Entity) => T): T {
209+
addComponent<T extends new (entity: Entity, ...args: any[]) => Component>(
210+
type: T,
211+
...args: ComponentArguments<T>
212+
): InstanceType<T> {
209213
ComponentsDependencies._addCheck(this, type);
210-
const component = new type(this);
214+
const component = new type(this, ...args) as InstanceType<T>;
211215
this._components.push(component);
212216
component._setActive(true, ActiveChangeFlag.All);
213217
return component;
@@ -751,3 +755,10 @@ export class Entity extends EngineObject {
751755
return this._invModelMatrix;
752756
}
753757
}
758+
759+
type ComponentArguments<T extends new (entity: Entity, ...args: any[]) => Component> = T extends new (
760+
entity: Entity,
761+
...args: infer P
762+
) => Component
763+
? P
764+
: never;

packages/xr/src/XRManagerExtended.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ export class XRManagerExtended extends XRManager {
6060
override addFeature<T extends new (xrManager: XRManagerExtended, ...args: any[]) => XRFeature>(
6161
type: T,
6262
...args: TFeatureConstructorArguments<T>
63-
): XRFeature | null {
63+
): InstanceType<T> | null {
6464
if (this.sessionManager._platformSession) {
6565
throw new Error("Cannot add feature when the session is initialized.");
6666
}
@@ -69,7 +69,7 @@ export class XRManagerExtended extends XRManager {
6969
const feature = features[i];
7070
if (feature instanceof type) throw new Error("The feature has been added");
7171
}
72-
const feature = new type(this, ...args);
72+
const feature = new type(this, ...args) as InstanceType<T>;
7373
this._features.push(feature);
7474
return feature;
7575
}

0 commit comments

Comments
 (0)