在 Three.js 中,
尽管这样做确实覆盖了
是否有一种方法可以将类型声明合并,从而仅覆盖
Object3D
类有一个名为 userData 的字段,它在类型声明文件 node_modules/three/src/core/Object3D.d.ts
中定义为:/**
* Base class for scene graph objects
*/
export class Object3D extends EventDispatcher {
[...]
/**
* An object that can be used to store custom data about the Object3d. It should not hold references to functions as these will not be cloned.
* @default {}
*/
userData: { [key: string]: any };
[...]
}
我希望更加强化userData的类型检查,所以我创建了一个模块类型声明src/typings/three.d.ts
:
declare module 'three' {
export class Object3D {
userData: MyType1 | MyType2;
}
}
type MyType1 = {
type: 'type1';
radius: number;
};
type MyType2 = {
type: 'type2';
name: string;
};
尽管这样做确实覆盖了
userData
属性,但它并没有进行合并,而是覆盖了three
模块中的所有类型声明,这使得更改比有用更具破坏性(请注意其他属性的缺失)。
![在vscode中缺少类型声明](https://istack.dev59.com/VQZtG.webp)
userData
而不是整个模块?
getObjectByName
仍然返回原始的Object3D类型,而不是被覆盖的类型。请参见https://codesandbox.io/s/stackoverflow-module-augmentation-forked-47yev7 - Mitchell Loeppky