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

如何在TypeScript中使用导入的命名空间定义interface/自定义类型

问题核心原因

你的代码存在两处关键错误导致校验不生效:

  1. 导入的Foo是运行时值,不能直接用keyof Foo取类型,需要先用typeof关键字拿到它的类型后再取键
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:54:08