如何在TypeScript中使用导入的命名空间定义interface/自定义类型
问题核心原因
你的代码存在两处关键错误导致校验不生效:
- 导入的
Foo是运行时值,不能直接用keyof Foo取类型,需要先用typeof关键字拿到它的类型后再取键 bar.js中你给Bar显式标注了{ [key: string]: string }类型,会抹掉具体的键名字面量类型,导致keyof Bar直接变成宽泛的string类型,无法约束值的范围
正确实现步骤
1. 修正bar文件的类型定义
去掉不必要的宽类型注解,让TypeScript自动推导Bar的具体键类型,必要时可以加as const固化类型:
// bar.ts 或 bar.js export const Bar = { stringA: 'some string', stringB: 'some string', } as const;
2. 修正类型定义逻辑
import * as Foo from './foo'; import { Bar } from './bar'; // 取foo模块所有导出名的字面量联合:"ObjA" | "ObjB" type MyTypes = keyof typeof Foo; // 取Bar所有键的字面量联合:"stringA" | "stringB" type BarAllowedKeys = keyof typeof Bar; // 最终约束对象类型 type MyType = { [typeName in MyTypes]: BarAllowedKeys; };
3. 校验效果符合预期
const newObject: MyType = { ObjA: 'stringA', // 校验通过 fooKey: 'stringB', // 键非法,校验失败:不存在fooKey属性 ObjB: 'fail', // 值非法,校验失败:fail不属于允许的字符串范围 barKey: 'randomValue', // 键和值均非法,校验失败 }
内容的提问来源于stack exchange,提问作者brewster
相关产品推荐
相关产品推荐

