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

TypeScript中如何将参数定义为值类型固定的任意接口

解决方案

要实现只接收所有属性值为boolean | string的任意接口,你可以通过泛型约束定义函数参数类型,确保传入的类型满足所有属性值的类型要求:

// library function
function print<T extends { [K in keyof T]: boolean | string }>(thing: T) {
    console.log(thing);
}

// user defined interface
interface Machine {
    powered: boolean;
}

interface Animal {
    sound: string;
}

interface Person {
    age: number;
}

let blender: Machine = { powered: false };
let cat: Animal = { sound: "meow" };
let person: Person = { age: 24 };

print(blender); // ✅ 正常通过
print(cat);     // ✅ 正常通过
print(person);  // ❌ 类型错误:类型“Person”不满足约束“{ [K in keyof Person]: boolean | string }”

原理说明

  • 泛型参数T被约束为:T的每一个属性K对应的类型T[K]必须是boolean | string。
  • TypeScript会自动检查传入的类型是否符合这个约束:只要有任意一个属性的类型不是boolean或string,就会触发类型错误,完全匹配你的需求。

为什么不用Record<string, boolean | string>?

直接用Record<string, boolean | string>作为参数类型时,虽然大部分符合条件的接口实例可以传入,但对于带有明确属性名的接口(比如Machine),TypeScript的类型检查会更严格,可能出现不必要的兼容性提示。而泛型约束的方式更灵活,能完美适配用户自定义的任意接口,只要接口的属性值类型符合要求即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:20:20