从模块自己的导出键生成类型
Generate a type from a module's own exported keys
给出这样的模块:
export const a: string;
export const b: string;
从外部你可以生成这样的类型 "a" | "b"
:
import * as stuff from "./stuff";
type StuffKeys = keyof typeof stuff; // "a" | "b"
但我想从 模块 中生成并导出此类型。类似于:
export type MyKeys = keyof typeof this;
但这不起作用。
有办法吗?
我不相信,您计划做的事情是可能的,因为行 export type MyKeys...
需要包含在键类型本身中。
然而,令人惊讶的是,它正在努力将模块导入自身并从那里导出密钥。
main.ts
export const a : string = 'a';
export const b : string = 'b';
import * as main from './main'
export type MyKeys = keyof typeof main;
test.ts
import {MyKeys} from './main';
const a : MyKeys = 'a';
const b : MyKeys = 'c'; // TS2322: Type '"c"' is not assignable to type '"a" | "b"'.
给出这样的模块:
export const a: string;
export const b: string;
从外部你可以生成这样的类型 "a" | "b"
:
import * as stuff from "./stuff";
type StuffKeys = keyof typeof stuff; // "a" | "b"
但我想从 模块 中生成并导出此类型。类似于:
export type MyKeys = keyof typeof this;
但这不起作用。
有办法吗?
我不相信,您计划做的事情是可能的,因为行 export type MyKeys...
需要包含在键类型本身中。
然而,令人惊讶的是,它正在努力将模块导入自身并从那里导出密钥。
main.ts
export const a : string = 'a';
export const b : string = 'b';
import * as main from './main'
export type MyKeys = keyof typeof main;
test.ts
import {MyKeys} from './main';
const a : MyKeys = 'a';
const b : MyKeys = 'c'; // TS2322: Type '"c"' is not assignable to type '"a" | "b"'.