2017-02-14 88 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"'.