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

如何让TypeScript泛型参数必填以限制GridSelectProps输入?

强制GridSelectProps泛型参数必填并限制输入类型

要实现泛型参数必填,仅允许传入对应类型的键值,可通过以下方式修改代码:

解决方案思路

给泛型参数T添加显式对象类型约束,同时不提供默认类型(或设置默认类型为never),强制用户必须显式指定泛型类型,避免TypeScript自动推断出宽松类型导致任意字符串通过校验。

修改后的代码示例

interface Person {
  Id: number;
  Name: string;
}

// 约束Props的泛型T必须是对象类型
interface Props<T extends object> {
  readonly dataItemKey: keyof T & string;
}

// 泛型T设为必须继承object,不提供默认值,强制用户显式指定
const GridSelectProps = <T extends object>({ dataItemKey }: Props<T>): GridProps => {
  return {
    dataItemKey,
  };
};

// ❌ 编译器报错:不指定泛型时,T被推断为{},keyof {}为never,无法匹配字符串"Test"
const somePropsWithout = GridSelectProps({
  dataItemKey: "Test" 
});

// ✅ 正常校验:仅允许传入Person类型的键
const somePropsWith = GridSelectProps<Person>({
  dataItemKey: "Id",
});

// ❌ 编译器报错:"Test"不是Person类型的有效键
const somePropsWrong = GridSelectProps<Person>({
  dataItemKey: "Test"
});

另一种实现方式(默认类型为never)

如果希望更明确禁止不指定泛型的情况,可将泛型默认值设为never:

const GridSelectProps = <T extends object = never>({ dataItemKey }: Props<T>): GridProps => {
  return {
    dataItemKey,
  };
};

此时不指定泛型时,T为never,keyof never同样是never,dataItemKey无法传入任何有效值,进一步强制用户必须显式指定泛型类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:22:44