keyof typeof 模块不适用于接口

时间:2021-07-19 15:27:14

标签: typescript

我想创建一个动态类型,它是接口符号的联合。 给定一个文件“MyInterfaces.ts”

export interface SomeInterfaceA {}
export interface SomeInterfaceB {}
...
export interface SomeInterfaceZ {}

我有以下定义:

import * as AllMyInterfaces from "./MyInterfaces"

type InterfaceNames = keyof typeof AllMyInterfaces
const test: InterfaceNames = "SomeInterfaceA"
//^^^^^^^^^ TS2322: Type 'string' is not assignable to type 'never'.

但是编译器说:“string”类型不能分配给“never”类型

不知何故,“typeof AllMyInterfaces”的结果不包含任何接口符号。 我必须如何定义我的联合类型才能使其工作? 谢谢

1 个答案:

答案 0 :(得分:1)

导出的类型(例如接口)实际上不会向导出的模块添加任何内容。因此,keyof 类型运算符会忽略星形导入的“类型字段”。

使用此示例模块显示时,这也更直观:

export const ABC = 123;
export type Def = number;

以下代码将产生以下输出:

import * as MyModule from './module';
Object.keys(MyModule); // ['ABC']

所以 keyof 运算符忽略类型是有道理的。

相关问题