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

如何创建自定义TypeScript类型错误?嵌套options后仍生效

问题

我现有一段TypeScript代码,传入特定参数组合时会抛出自定义类型错误,目前功能正常。现在需要把display字段嵌套进options对象中,怎么操作才能保留原有的类型错误校验功能?

原有可正常运行的代码:

type CheckForIncompatibleArgs<Args> = Args extends { heading: false; link: true } ? "You cannot display a link without a heading" : Args;

type Display = {heading: boolean; link: boolean};

interface Props<T> {
    display: CheckForIncompatibleArgs<T>;
    hello: string;
}

const fn = <T extends Display>({display, hello}: Props<T>) => {
    console.log("display heading:", display.heading);
    console.log("display link:", display.link);
}

// ✅ 合法调用
fn({display: { heading: true, link: true}, hello: "yes"});
fn({display: { heading: true, link: false}, hello: "yes"});

// ❌ 非法调用,触发类型错误
fn({display: { heading: false, link: true}, hello: "yes"});

需要修改为如下结构,同时保留类型错误校验:

interface Props {
    options: {
        display: Display;
    };
    hello: string;
}
解决方案

只需将类型校验逻辑迁移到options.display字段上,通过泛型约束和条件类型的组合即可实现,修改后的完整代码如下:

type CheckForIncompatibleArgs<Args> = Args extends { heading: false; link: true } ? "You cannot display a link without a heading" : Args;

type Display = {heading: boolean; link: boolean};

// 重新定义带泛型的Props接口,将校验逻辑应用到options.display上
interface Props<T> {
    options: {
        display: CheckForIncompatibleArgs<T>;
    };
    hello: string;
}

// 调整函数的泛型约束和解构逻辑
const fn = <T extends Display>({options: {display}, hello}: Props<T>) => {
    console.log("display heading:", display.heading);
    console.log("display link:", display.link);
}

// ✅ 合法调用
fn({options: { display: { heading: true, link: true}}, hello: "yes"});
fn({options: { display: { heading: true, link: false}}, hello: "yes"});

// ❌ 非法调用,触发类型错误
fn({options: { display: { heading: false, link: true}}, hello: "yes"});

说明

  • 保留原有的CheckForIncompatibleArgs条件类型,它会在检测到heading: false且link: true的非法组合时返回错误字符串,触发TypeScript类型检查报错。
  • 泛型T仍约束为Display,确保传入的display结构始终符合{heading: boolean; link: boolean}的基本格式。
  • 函数参数通过解构options.display获取字段,内部逻辑与原有代码一致,不影响功能运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:07:06