You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让用户重写@hakit/core包中的SupportedServices类型?

实现TypeScript包中自定义类型优先、默认类型兜底的方案

我开发的@hakit/core包用于Home Assistant实例自动化,其中提供了SupportedServices类型。由于用户的Home Assistant配置差异极大,我需要让用户能够完全重定义这个类型。

一开始我提供了根据当前实例生成接口的脚本,但遇到了TypeScript的限制:它只支持类型扩展,无法直接替换原有类型。尝试使用模块扩展的方式后,包内的内部函数依然指向原类型,达不到完全替换的效果。

最终我找到了可行的解决方案:在包内定义一个空接口CustomServicesContainer,通过条件类型判断SupportedServices到底使用用户的自定义类型还是默认类型。用户只需要扩展这个空接口,就能实现对SupportedServices类型的完全替换。

包内实现代码

// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface CustomServicesContainer<T extends ServiceFunctionTypes = "target"> {
  
}

export type SupportedServices<T extends ServiceFunctionTypes = "target"> = [keyof CustomServicesContainer<T>] extends [never] ? DefaultServices<T> : CustomServicesContainer<T>

用户侧使用代码

import { ServiceFunction, ServiceFunctionTypes } from "@hakit/core";

declare module "@hakit/core" {
  export interface CustomServicesContainer<T extends ServiceFunctionTypes = "target"> {
    computer: {
      turnOn: ServiceFunction<
        T,
        {
          apples: number;
        }
      >;
    };
  }
}

内容的提问来源于stack exchange,提问作者Shannon Hochkins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:55:05