能否把 cc.d.ts文件的补充写在自己的工程里面?

比如我直接在Button 的prototype定义自己的函数

Button.prototype.subscribe = function () {}

我就需要修改cc.d.ts 文件。但是cc.d.ts 在引擎的全局目录下。如何能跟工程走呢?或者是否能把我修改的这部分写在工程目录下的哪个.d.ts里面。

export class Button extends Component {
subscribe: () => void;

另外我也查询了
3.x 自定义的d.ts文件里面的类怎么继承自cc.d.ts里面提供的类? - Creator 3.x - Cocos中文社区
[提问]:d.ts声明文件的编写 - Creator 2.x - Cocos中文社区
这两个主题,但是我需要修改Button,能否把 Button的类型定义分些在两个地方?或者有没有更好的方案。

上面的subscribe是个例子,实际里面要返回一个引用当前工程的类型,所以也更不合适放进全局的cc.d.ts

可以的

declare namespace cc {
    interface Button {
        template(): void;
    }
}
// ... 赋值语句

我写了个common.d.ts在工程目录下。
里面就照你说的方式写了:


但是不能直接起作用,还需要关联关联这个文件吗?

写在ts文件里

declare module "cc" {
  interface Button {
    // ...
  }
}
1赞

好的,最后是这样的:

import { Subscription } from 'rxjs';
import { Observable, EMPTY } from 'rxjs';
import { Button, isValid, warn } from "cc";

export function BindButton(button: Button): Observable<Button> {
    if (!button) { warn('BindButton, button is null'); return EMPTY; }
    return new Observable(observer => {
        const clickCallback = param => observer.next(param);
        button.node.on(Button.EventType.CLICK, clickCallback);
        return () => {
            if (isValid(button.node)) {
                button.node.off(Button.EventType.CLICK, clickCallback);
            }
        }
    })
}

declare module "cc" {
    interface Button {
        subscribe: (callback: (param: any) => void, target: any) => Subscription
    }
}

Button.prototype.subscribe = function (callback: (param: any) => void, target): Subscription {
    return BindButton(this).subscribe(callback.bind(target));
};
2赞