gpt4 book ai didi

typescript - 如何在模块本身内部为模块定义类型?

转载 作者:搜寻专家 更新时间:2023-10-30 21:09:54 25 4
gpt4 key购买 nike

假设我有一个名为 hello-service.ts 的 typescript 文件:

export function hello1() { ... }
export function hello2() { ... }
export function hello3() { ... }

在某些情况下,我们需要这个模块的类型。我们可以像这样在另一个 ts 文件中引用它:

import * as helloService from './hello-service.ts';

function getHelloModule(): typeof helloService {
return hello;
}

但我想知道,是否可以在 hello-service.ts 文件本身的内部定义这样的类型?

目前,我只能通过指定每个功能来实现这一点,这很无聊:

export type HelloServiceType = {
hello1: typeof hello1,
hello2: typeof hello2,
hello3: typeof hello3
}

有没有更简单的解决方案?

最佳答案

您可以将导入类型称为 typeof import('./hello-service.ts')。这肯定会在模块外部工作。我从来没有在模块中使用过它,但根据我的尝试,它可以按预期工作,即使它有点递归:

// ./hello-service.ts
export function hello1() { }
export function hello2() { }
export function hello3() { }


declare var exports: Self;
type Self = typeof import('./hello-service')
export let self: Self = exports;

// usage.ts

import * as hello from './hello-service'
hello.self.hello1()

关于typescript - 如何在模块本身内部为模块定义类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53970486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com