给出这样的模块:
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;
但这不起作用。
有办法做到这一点吗?
答案 0 :(得分:2)
我不相信,你计划做的事情是可能的,因为行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"'.