typescript - Typescript - 从模块导入的任何类型
问题描述
我有类似的东西:
import * as Types from '../schema/types';
我想做类似的事情:
let a: Types;
表示它a
必须是从 导出的多种类型之一types.ts
。我怎样才能做到这一点?(是的,它是一个 graphql 服务器)
解决方案
看起来你的意图是使用union types
. 对于打字稿union types
,您可以参考以下示例 -
场景一:在其他模块中构造个别类型,使用过程中使用union:
类型.ts
type a = {
name: string;
}
type b ={
name: number;
}
export type {a, b}
你可以像这样使用它:
import {a,b} from './types';
let a: a|b;
或者
import * as types from './types';
let a: types.a|types.b;
场景二:在其他模块中构造联合类型,在调用端使用:
类型.ts
type a = {
name: string;
}
type b ={
id: string;
}
export type types = a|b
用它
import {types} from './types';
let a: types;
为了使用联合类型在graphql
使用中提到的例子here
-
更新:在看到您关于获取所有类型的评论后,答案是否定的。和属于世界上甚interfaces
至不存在的,它们只是编译器提示对象具有特定结构。换句话说,您甚至无法从模块中获取所有类型并像在这些甚至不存在于运行时中那样分配它们。types
type space
JS
Object.Keys/ Object.entries
classes.
您最好的选择是从模块中提取它们并union types
在 types.ts 文件中转换或构造联合类型并在主文件中使用它们。
推荐阅读
- angular - 如何更新列表中的对象
- javascript - 从十字准线到工具提示的 Highcharts 距离
- sql - SQL 转换动态查询生成限制
- node.js - 如何在 WebStorm 中调试 firebase 云功能?
- android - 在我的 CI 上初始化 gradle 时出现错误
- html - 如何让页脚宽度达到全屏
- php - 使用两个表在留言簿中显示条目的作者 (myphpadmin)
- java - ArrayList 优化内存
- python - 使用python将数据从.csv导入mysql到两个表中
- .net-core - 如何验证参数 ID 和令牌声明 ID 与授权标签相同