如何在TypeScript中提取接口指定键的类型?
TypeScript 从已有接口提取特定键的类型实现方法
完全可以实现,你可以用TypeScript的索引类型查询语法直接从已定义的接口中提取特定键对应的类型,不用重复定义。
针对你的示例代码,只需要把PooProps里的wantType类型改成Props['certainType']即可:
interface Props { aType: number; bType: string; certainType: 'a' | 'b' | 'c'; } interface PooProps { cType: boolean; wantType: Props['certainType']; // 直接提取Props中certainType的类型 } function foo(value: PooProps){} const result = foo({cType: true, wantType: 'a'}) // 类型校验正常 const errorResult = foo({cType: true, wantType: 'd'}) // 会触发类型错误,符合预期
补充说明
- 这种语法的核心是
Type['Key'],它会直接返回Type接口中Key对应的类型,后续如果Props里的certainType类型发生变更,wantType的类型会自动同步,避免重复维护的麻烦。 - 如果需要提取多个键对应的类型,可以使用
Pick工具类型,比如Pick<Props, 'aType' | 'certainType'>,它会生成一个包含指定键的新类型。
内容的提问来源于stack exchange,提问作者Brian
相关产品推荐
相关产品推荐

