【问题标题】:Generate a type from a module's own exported keys从模块自己的导出键生成类型
【发布时间】:2017-07-02 23:38:08
【问题描述】:

给定一个这样的模块:

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;

但这不起作用。

有没有办法做到这一点?

【问题讨论】:

    标签: typescript typescript2.1


    【解决方案1】:

    我不相信您计划做的事情是可能的,因为 export type MyKeys... 行需要包含在键类型本身中。

    然而,令人惊讶的是,它只是将模块导入自身并从那里导出密钥。

    ma​​in.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"'.
    

    【讨论】:

    • 请注意,如果您想在同一个模块中定义类型,假设它被称为foo.ts,您可以执行以下操作: type Exports = keyof typeof import('./foo')
    猜你喜欢
    • 1970-01-01
    • 2017-11-05
    • 2021-11-25
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    相关资源
    最近更新 更多