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

TypeScript中无需使用泛型<T>时,能否省略其声明语法?

TypeScript 实现可选泛型参数的正确方式

TypeScript 本身支持泛型默认参数语法,完全可以实现你想要的「不用泛型时直接用Props,需要时再指定Props<T>」的需求,不需要自定义<?T>这种非标准语法。

正确的接口定义方式

给泛型参数指定默认类型,就能让它成为可选参数:

interface Props<T = undefined> {
  className: string;
  data?: T;
}

使用示例

  • 不指定泛型时,直接用Props类型,此时data的类型为undefined,仅传入className完全合法:
const props: Props = { className: "hello, world" };
  • 需要携带数据时,指定具体的泛型类型:
const propsWithData: Props<{ something: string }> = {
  className: "hw",
  data: { something: "something" }
};

进阶:限制无泛型时不能传data

如果希望不指定泛型时,data字段完全不能被赋值(而非允许传undefined),可以把默认类型设为never:

interface Props<T = never> {
  className: string;
  data?: T;
}

// 下面的代码会触发类型错误,符合预期
// const invalidProps: Props = { className: "test", data: {} };

内容的提问来源于stack exchange,提问作者レノキ乇1ᑌᑭ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:17:21