【问题标题】:keyof typeof Module not working with interfaceskeyof typeof 模块不适用于接口
【发布时间】:2021-07-19 23:50:10
【问题描述】:

我想创建一个动态类型,它是接口符号的联合。 给定一个文件“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”的结果不包含任何接口符号。 我必须如何定义我的 Union 类型才能使其工作? 谢谢

【问题讨论】:

    标签: typescript


    【解决方案1】:

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

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

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

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

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

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

    【讨论】:

    • 嗯,感谢您到目前为止对原因的解释。你有解决这个问题的办法吗?如何收集接口?
    • 您可以创建另一个接口,其中包含这些其他接口作为字段。例如。 interface AllMyInterfaces { SomeInterfaceA: SomeInterfaceA; } 允许您使用 keyof AllMyInterfaces (即使在任何地方导入该类型之后)
    • 这将与将 InterfaceNames 定义为 type InterfaceNames = "SomeInterfaceA" | "SomeInterfaceB" | ... | "SomeInterfaceZ" 相同(工作量/类型连接松散)有大量的接口,它们可能会不时更改。所以我真的需要一些通用的解决方案。
    • @Zomono 正确,但您无能为力。您总是可以尝试在 GitHub 上的 TypeScript 存储库上提出功能请求(甚至是拉取请求),但这当然是一个漫长的过程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2022-01-09
    • 2014-07-16
    • 1970-01-01
    • 2022-06-10
    • 2021-02-07
    • 1970-01-01
    相关资源
    最近更新 更多