首页 > 解决方案 > Typescript - 从模块导入的任何类型

问题描述

我有类似的东西:

import * as Types from '../schema/types';

我想做类似的事情:

let a: Types;

表示它a必须是从 导出的多种类型之一types.ts。我怎样才能做到这一点?(是的,它是一个 graphql 服务器)

标签: typescriptgraphql

解决方案


看起来你的意图是使用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至不存在的,它们只是编译器提示对象具有特定结构。换句话说,您甚至无法从模块中获取所有类型并像在这些甚至不存在于运行时中那样分配它们。typestype spaceJSObject.Keys/ Object.entriesclasses.

您最好的选择是从模块中提取它们并union types在 types.ts 文件中转换或构造联合类型并在主文件中使用它们。


推荐阅读