从另一个文件中导入声明时要尽量减少重复?

时间:2019-01-31 10:53:28

标签: typescript

我已将声明移到一个单独的文件中,以使文件更短。下面是我导入它们的方式。

client-types.ts

declare module 'client-types' {
    export interface IRequestBody { type: 'request' }
    export interface CreateProjectRequestBody extends IRequestBody { cmd: 'otii_create_project' }
    export interface GetArcsRequestBody extends IRequestBody { cmd: 'otii_get_devices' }
    export interface OpenProjectRequestBody extends IRequestBody { cmd: 'otii_open_project', payload: { value: string, force: boolean, progress: boolean } }

    export interface IResponse {}
    export interface CreateProjectResponse extends IResponse { payload: { project_id: number } }
    export interface GetArcsResponse extends IResponse { payload: { devices: [ { device_id: number, name: string, type: string } ] } }
    export interface OpenProjectResponse extends IResponse { payload: { project_id: string } }

    export interface ResponseDevice { device_id: number, name: string, type: string }

    export interface CreateProjectResponseData { id: number }
    export interface GetArcsResponseData { [index: number]: {id: number, name: string} }
    export interface OpenProjectResponseData { id: number }
}

index.ts

// imports
import { 
    IRequestBody, 
    CreateProjectRequestBody, 
    GetArcsRequestBody, 
    OpenProjectRequestBody,
    IResponse,
    CreateProjectResponse,
    GetArcsResponse,
    OpenProjectResponse,
    ResponseDevice,
    CreateProjectResponseData,
    GetArcsResponseData,
    OpenProjectResponseData
} from 'client-types';

// use
request(body: CreateProjectRequestBody) : Promise<CreateProjectResponse>
request(body: GetArcsRequestBody) : Promise<GetArcsResponse>
request(body: OpenProjectRequestBody) : Promise<OpenProjectResponse>
request<T extends IRequestBody>(body: T): Promise<IResponse> {
    ...
}

async createProject() : Promise<CreateProjectResponseData> { 
    ...
}

我不喜欢必须在import语句中编写每种类型。我更喜欢以下内容:

import * from from 'client-types';

但是我得到了错误[ts] 'as' expected.

有没有一种方法可以消除这种重复(对我而言),还是我已经在使用“最佳实践”?

PS:我编写的代码将成为npm软件包。让我知道您是否认为与该问题有关的任何特定于npm的信息。

1 个答案:

答案 0 :(得分:2)

您可以这样做:

import * as clientTypes from 'client-types';

然后使用clientTypes.CreateProjectRequestBody代替CreateProjectRequestBody,等等。

但是好的IDE应该在编写类型时自动导入类型。

另请参阅:ES6 In Depth: Modules