2017-02-14 82 views
1

一种给定一个模块是这样的:生成模块自身的出口键

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; 

但这并不奏效。

有没有办法做到这一点?

回答

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"'.