I have something like:
import * as Types from '../schema/types';
and I wanna do something like:
let a: Types;
indicating that a
has to be one of the multiple types exported from types.ts
. How can I do that? (Yes it's a graphql server)
Looks like you are intention is to use union types
. For typescript union types
you can refer below sample example -
Scenario 1: Construct individual types in other module and use union during the usage:
types.ts
type a = {
name: string;
}
type b ={
name: number;
}
export type {a, b}
You can use it like:
import {a,b} from './types';
let a: a|b;
Or
import * as types from './types';
let a: types.a|types.b;
Scenario 2: Construct union types in other module and use in calling side:
types.ts
type a = {
name: string;
}
type b ={
id: string;
}
export type types = a|b
Use it
import {types} from './types';
let a: types;
For using the union types in graphql
use the example mentioned here
-
Update: After seeing your comments regarding getting all the types the answer is NO . The interfaces
and types
fall under the type space
which dont even exist in the JS
world and they are just compiler hints for objects to have specific structure. In other words you even cannot do the Object.Keys/ Object.entries
to get all the types from the module and assign them like you do in classes.
These dont even exist in the run time.
Your best bet would be to extract them from the module and convert to union types
or construct the union type in the types.ts file and use them in the main file.
I can't think of a way to do it automatically, but what you need is a union type .
Assuming you have the following types declared in the ../schema/types
:
interface Foo {
...
}
interface Bar {
...
}
imported with import * as Types from '../schema/types';
You can create a union type like:
type GqType = Types.Bar | Types.Foo;
Then you can create a
like:
let a: GqType;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.