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

如何在TypeScript中确保接口两个属性类型一致?

实现类型一致的Example接口

要让value和otherValueToCompare支持任意类型但必须保持类型一致,你可以用泛型接口来实现——泛型能在定义接口时动态指定类型,同时约束两个属性使用相同的类型。

定义泛型接口

interface Example<T> {
  value: T;
  otherValueToCompare: T;
}

使用示例

根据需要传入具体的类型参数,两个属性就会被约束为该类型:

  • 字符串类型示例:
const stringDemo: Example<string> = {
  value: "foo",
  otherValueToCompare: "bar"
};
  • 数字类型示例:
const numberDemo: Example<number> = {
  value: 100,
  otherValueToCompare: 200
};
  • 自定义类型示例:
type User = { id: number; name: string };
const userDemo: Example<User> = {
  value: { id: 1, name: "Alice" },
  otherValueToCompare: { id: 2, name: "Bob" }
};

类型校验

如果尝试给两个属性传入不同类型的值,TypeScript会直接抛出错误:

// 报错:类型 'number' 不能赋值给类型 'string'
const invalidDemo: Example<string> = {
  value: "test",
  otherValueToCompare: 123
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:24:10